<template>
  <div class="app-container home">
    <!--  ------------------------------第一排按钮+第一个表格控件  -->
    <el-container>
      <!-- 统一的筛选区域 - 包含按钮和搜索框 -->
      <el-header style="height: 300px; border: 1px solid #e4e7ed; background-color: #f5f7fa; border-radius: 6px; margin-bottom: 20px;">
        <div style="padding: 15px 20px;">
          <el-form :inline="true" :model="form" size="small">
            <!-- 第一行：操作按钮 -->
            <div style="margin-bottom: 15px; display: flex; align-items: center; justify-content: flex-start;">
              <el-button type="primary" @click="selectData" icon="el-icon-search" size="medium">搜索</el-button>
              <el-button type="warning" @click="clearSerch" icon="el-icon-refresh" size="medium" style="margin-left: 10px;">清除查询</el-button>
              <el-button type="success" @click="daochu" icon="el-icon-download" size="medium" style="margin-left: 10px;">导出</el-button>
            </div>

            <!-- 第二行：主要筛选条件 -->
            <div style="margin-bottom: 15px; display: flex; align-items: flex-start; flex-wrap: wrap; min-height: 60px;">
              <el-form-item label="日期" style="margin-right: 20px; margin-bottom: 0;">
                <el-date-picker
                  v-model="form.dateOption"
                  type="daterange"
                  range-separator="至"
                  @change="remoteMethod"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 265px;">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="文件名" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.fileNames"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择文件名"
                  style="width: 400px;"
                  @visible-change="handleFileNameVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="试样号" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.syNumbers"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择试样号"
                  style="width: 400px;"
                  @visible-change="handleSyNumberVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.options2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="试样类型" style="margin-bottom: 0;">
                <el-select
                  v-model="form.sampleTypes"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择试样类型"
                  style="width: 300px;"
                  @visible-change="handleSampleTypeVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.sampleTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>

            <!-- 第三行：详细筛选条件 -->
            <div style="display: flex; align-items: flex-start; flex-wrap: wrap; min-height: 80px;">
              <el-form-item label="取样位置" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.samplingPositions"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择取样位置"
                  style="width: 470px;"
                  @visible-change="handleSamplingPositionVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.samplingPositionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="取样工序" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.samplingProcesses"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择取样工序"
                  style="width: 470px;"
                  @visible-change="handleSamplingProcessVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.samplingProcessOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="作图名称" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.chartNames"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择作图名称"
                  style="width: 460px;"
                  @visible-change="handleChartNameVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.chartNameOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 第四行：详细筛选条件 -->
            <div style="display: flex; align-items: flex-start; flex-wrap: wrap; min-height: 40px;">
              <el-form-item label="出钢记号" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.steelMarks"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择出钢记号"
                  style="width: 380px;"
                  @visible-change="handleSteelMarkVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.steelMarkOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="取样时间" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.samplingTimes"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择取样时间"
                  style="width: 380px;"
                  @visible-change="handleSamplingTimeVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.samplingTimeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="送样人" style="margin-right: 20px; margin-bottom: 0;">
                <el-select
                  v-model="form.submitters"
                  multiple
                  filterable
                  collapse-tags
                  placeholder="请选择送样人"
                  style="width: 380px;"
                  @visible-change="handleSubmitterVisibleChange"
                  @change="onConditionChange">
                  <el-option
                    v-for="item in form.submitterOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" style="margin-bottom: 0;">
                <el-input
                  v-model="form.remarks"
                  placeholder="请输入备注关键词"
                  style="width: 215px;"
                  @input="onConditionChange">
                </el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-header>

      <!-- 保留原有的对话框 -->
      <el-dialog
        title="提示"
        v-loading="loading"
        :visible.sync="dcdialogVisible"
        width="40%"
        :before-close="handleClose1">
        <span>请选择生成的数据</span>
        <div>
          <el-checkbox v-model="checked5" :disabled="disabled5" label="表1" border></el-checkbox>
          <el-checkbox v-model="checked6" :disabled="disabled6" label="表2" border></el-checkbox>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dcdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="exportTable">确 定</el-button>
        </span>
      </el-dialog>
    </el-container>


    <el-container>
      <el-main style="padding: 0">
        <el-card style="margin-bottom: 20px">
          <ux-grid
            border
            stripe
            :data="tableData1"
            style="width: 100%"
            height="330px"
            align="center">
            <ux-table-column
              fixed
              align="center"
              field="DT"
              title="时间"
              width="170">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="SNUMB"
              title="序号"
              width="85">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="excel_name"
              title="文件名"
              width="100">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="IDNO"
              title="特征"
              width="85">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="section"
              title="区域"
              width="100">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="inclusion_type"
              title="夹杂物分类"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="FOV"
              title="视场"
              width="50">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="ECD"
              title="ECD((µm))"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="area"
              title="面积(µm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="shape"
              title="形状"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="length"
              title="长度(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="perimeter"
              title="周长(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="aspect"
              title="纵横比"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="X_axis"
              title="样品台X轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Y_axis"
              title="样品台Y轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="excel2_name"
              title="面积表文件名"
              width="170">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="PONO"
              title="PONO"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_type"
              title="试样类型"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_location"
              title="取样位置"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_process"
              title="取样工序"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="analysis_area"
              title="分析面积(mm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="chart_name"
              title="作图名称"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="casting_mark"
              title="出钢记号"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_time"
              title="取样时间"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_sender"
              title="送样人"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Remarks"
              title="备注"
              width="300">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Li_wt_percent"
              title="Li (重量百分比)"
              width="130">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="B_wt_percent"
              title="B (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="C_wt_percent"
              title="C (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="N_wt_percent"
              title="N (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="O_wt_percent"
              title="O (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="F_wt_percent"
              title="F (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Na_wt_percent"
              title="Na (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mg_wt_percent"
              title="Mg (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Al_wt_percent"
              title="Al (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Si_wt_percent"
              title="Si (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="P_wt_percent"
              title="P (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="S_wt_percent"
              title="S (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cl_wt_percent"
              title="Cl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="K_wt_percent"
              title="K (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ca_wt_percent"
              title="Ca (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ti_wt_percent"
              title="Ti (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="V_wt_percent"
              title="V (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cr_wt_percent"
              title="Cr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mn_wt_percent"
              title="Mn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Fe_wt_percent"
              title="Fe (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ni_wt_percent"
              title="Ni (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cu_wt_percent"
              title="Cu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="As_wt_percent"
              title="As (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Zr_wt_percent"
              title="Zr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Nb_wt_percent"
              title="Nb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mo_wt_percent"
              title="Mo (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ru_wt_percent"
              title="Ru (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Rh_wt_percent"
              title="Rh (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pd_wt_percent"
              title="Pd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cd_wt_percent"
              title="Cd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sn_wt_percent"
              title="Sn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sb_wt_percent"
              title="Sb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Te_wt_percent"
              title="Te (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="La_wt_percent"
              title="La (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ce_wt_percent"
              title="Ce (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pm_wt_percent"
              title="Pm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sm_wt_percent"
              title="Sm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Eu_wt_percent"
              title="Eu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Dy_wt_percent"
              title="Dy (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tm_wt_percent"
              title="Tm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Yb_wt_percent"
              title="Yb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ta_wt_percent"
              title="Ta (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tl_wt_percent"
              title="Tl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ra_wt_percent"
              title="Ra (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ac_wt_percent"
              title="Ac (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pa_wt_percent"
              title="Pa (重量百分比)"
              width="120">
            </ux-table-column>
          </ux-grid>
          <el-pagination
            background
            layout="prev, pager, next"
            @current-change="table1CurrentChange"
            :current-page="form.currentPage"
            :page-size="table1PageSize"
            :total="tableData1Total">
          </el-pagination>
        </el-card>
      </el-main>
    </el-container>
    <!--  ------------------------------第二个表格控件  -->
    <el-container>
      <el-header style="height: 50px">
        <div>
          <el-button
            type="primary"
            icon="el-icon-s-platform"
            @click="filterLowC"
          >
            二次清洗数据
          </el-button>
        </div>
      </el-header>
      <!-- <el-button
         icon="el-icon-s-platform"
         type="primary"
         @click="filterSi"
       >
       铝镇静钢
       </el-button>
       <el-button
         icon="el-icon-s-platform"
         @click="filterLowMaterial"
         type="primary">
         铝硅镇静钢和硅钢
       </el-button>
     </div>
   </el-header> -->
      <el-main style="padding: 0">
        <el-card style="margin-bottom: 20px">
          <ux-grid
            border
            stripe
            :data="tableData2"
            style="width: 100%"
            height="330px"
            align="center">
            <ux-table-column
              fixed
              align="center"
              field="DT"
              title="时间"
              width="170">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="SNUMB"
              title="序号"
              width="85">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="excel_name"
              title="文件名"
              width="100">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="IDNO"
              title="特征"
              width="85">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="section"
              title="区域"
              width="100">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="inclusion_type"
              title="夹杂物分类"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="FOV"
              title="视场"
              width="50">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="ECD"
              title="ECD(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="area"
              title="面积(µm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="shape"
              title="形状"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="length"
              title="长度(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="perimeter"
              title="周长(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="aspect"
              title="纵横比"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="X_axis"
              title="样品台X轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Y_axis"
              title="样品台Y轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="excel2_name"
              title="面积表文件名"
              width="170">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="PONO"
              title="PONO"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_type"
              title="试样类型"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_location"
              title="取样位置"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_process"
              title="取样工序"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="analysis_area"
              title="分析面积(mm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="chart_name"
              title="作图名称"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="casting_mark"
              title="出钢记号"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_time"
              title="取样时间"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_sender"
              title="送样人"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Remarks"
              title="备注"
              width="300">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Li_wt_percent"
              title="Li (重量百分比)"
              width="130">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="B_wt_percent"
              title="B (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="C_wt_percent"
              title="C (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="N_wt_percent"
              title="N (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="O_wt_percent"
              title="O (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="F_wt_percent"
              title="F (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Na_wt_percent"
              title="Na (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mg_wt_percent"
              title="Mg (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Al_wt_percent"
              title="Al (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Si_wt_percent"
              title="Si (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="P_wt_percent"
              title="P (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="S_wt_percent"
              title="S (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cl_wt_percent"
              title="Cl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="K_wt_percent"
              title="K (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ca_wt_percent"
              title="Ca (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ti_wt_percent"
              title="Ti (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="V_wt_percent"
              title="V (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cr_wt_percent"
              title="Cr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mn_wt_percent"
              title="Mn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Fe_wt_percent"
              title="Fe (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ni_wt_percent"
              title="Ni (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cu_wt_percent"
              title="Cu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="As_wt_percent"
              title="As (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Zr_wt_percent"
              title="Zr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Nb_wt_percent"
              title="Nb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mo_wt_percent"
              title="Mo (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ru_wt_percent"
              title="Ru (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Rh_wt_percent"
              title="Rh (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pd_wt_percent"
              title="Pd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cd_wt_percent"
              title="Cd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sn_wt_percent"
              title="Sn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sb_wt_percent"
              title="Sb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Te_wt_percent"
              title="Te (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="La_wt_percent"
              title="La (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ce_wt_percent"
              title="Ce (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pm_wt_percent"
              title="Pm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sm_wt_percent"
              title="Sm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Eu_wt_percent"
              title="Eu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Dy_wt_percent"
              title="Dy (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tm_wt_percent"
              title="Tm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Yb_wt_percent"
              title="Yb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ta_wt_percent"
              title="Ta (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tl_wt_percent"
              title="Tl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ra_wt_percent"
              title="Ra (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ac_wt_percent"
              title="Ac (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pa_wt_percent"
              title="Pa (重量百分比)"
              width="120">
            </ux-table-column>
          </ux-grid>
        </el-card>
      </el-main>
    </el-container>
    <!--  ------------------------------插入一个表格的控件作为       第三个表-->
    <el-container>
      <el-header style="height: 50px">
        <div>
          <el-button
            type="primary"
            icon="el-icon-s-platform"
            @click="JZWCustom"
          >
            夹杂物自定义筛选
          </el-button>
          <!-- 弹出的对话框 -->
          <el-dialog
            title="夹杂物自定义筛选"
            :visible.sync="dialogVisible2"
            width="50%"
            top="10vh"
            :modal-append-to-body="true"
            center
          >
          <div v-if="showTemplateButtons" style="margin-bottom: 15px; text-align: right; padding: 10px; background: #f5f5f5; border-radius: 4px;">
            <el-button size="small" type="success" icon="el-icon-document" @click="saveTemplate">
            保存模板
            </el-button>
            <el-button size="small" type="primary" icon="el-icon-folder-opened" @click="loadTemplate">
            加载模板
            </el-button>
          </div>
            <!-- 表格 -->
            <el-table
              :data="jzwTableData"
              border
              style="width: 100%; height: 100%;"
              height="60vh"
            >
              <el-table-column type="index" width="50" label="序号" align="center">
                <template slot-scope="scope">
                  {{ scope.row.index }}
                </template>
              </el-table-column>

              <!-- 夹杂物元素分类列 -->
              <el-table-column
                prop="jzwelement"
                label="夹杂物元素分类"
                align="center"
              >
                <template slot-scope="scope">
                  <div style="text-align: center;">{{ scope.row.jzwelement }}</div>
                </template>
              </el-table-column>

              <!-- 统计数量列 -->
              <el-table-column
                prop="jzwcount"
                label="统计数量"
                align="center"
              >
                <template slot-scope="scope">
                  <div style="text-align: center;">{{ scope.row.jzwcount }}</div>
                </template>
              </el-table-column>

              <!-- 类型列（可编辑） -->
              <el-table-column
                prop="jzwType"
                label="夹杂物类型"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.jzwType"
                    placeholder="请输入类型"
                    style="text-align: center;"
                  ></el-input>
                </template>
              </el-table-column>

              <!-- 勾选列 -->
              <el-table-column
                label="勾选"
                align="center"
                width="180"
              >
                <template slot="header" slot-scope="{}">
                  <div
                    style="display: flex; justify-content: center; width: 100%; height: 100%;"
                    @dblclick="handleHeaderDoubleClick"
                  >
                    勾选
                  </div>
                </template>
                <template slot-scope="scope">
                  <div style="display: flex; justify-content: center;">
                    <el-checkbox
                      v-model="scope.row.checked"
                    ></el-checkbox>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 对话框底部按钮 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible2 = false">取 消</el-button>
              <el-button type="primary" @click="JZWconfirmselection">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-header>
      <el-main style="padding: 0">
        <el-card style="margin-bottom: 20px">
          <ux-grid
            border
            stripe
            :data="jzwTableData2"
            style="width: 100%"
            height="330px"
            align="center">
            <ux-table-column
              fixed
              align="center"
              field="DT"
              title="时间"
              width="170">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="SNUMB"
              title="序号"
              width="85">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="excel_name"
              title="文件名"
              width="100">
            </ux-table-column>
            <ux-table-column
              fixed
              align="center"
              field="IDNO"
              title="特征"
              width="85">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="section"
              title="区域"
              width="100">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="inclusion_type"
              title="夹杂物分类"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="FOV"
              title="视场"
              width="50">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="ECD"
              title="ECD(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="area"
              title="面积(µm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="shape"
              title="形状"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="length"
              title="长度(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="perimeter"
              title="周长(µm)"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="aspect"
              title="纵横比"
              width="110">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="X_axis"
              title="样品台X轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Y_axis"
              title="样品台Y轴(mm)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="excel2_name"
              title="面积表文件名"
              width="170">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="PONO"
              title="PONO"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_type"
              title="试样类型"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_location"
              title="取样位置"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_process"
              title="取样工序"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="analysis_area"
              title="分析面积(mm2)"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="chart_name"
              title="作图名称"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="casting_mark"
              title="出钢记号"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sampling_time"
              title="取样时间"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="sample_sender"
              title="送样人"
              width="140">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Remarks"
              title="备注"
              width="300">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Li_wt_percent"
              title="Li (重量百分比)"
              width="130">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="B_wt_percent"
              title="B (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="C_wt_percent"
              title="C (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="N_wt_percent"
              title="N (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="O_wt_percent"
              title="O (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="F_wt_percent"
              title="F (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Na_wt_percent"
              title="Na (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mg_wt_percent"
              title="Mg (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Al_wt_percent"
              title="Al (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Si_wt_percent"
              title="Si (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="P_wt_percent"
              title="P (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="S_wt_percent"
              title="S (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cl_wt_percent"
              title="Cl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="K_wt_percent"
              title="K (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ca_wt_percent"
              title="Ca (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ti_wt_percent"
              title="Ti (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="V_wt_percent"
              title="V (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cr_wt_percent"
              title="Cr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mn_wt_percent"
              title="Mn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Fe_wt_percent"
              title="Fe (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ni_wt_percent"
              title="Ni (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cu_wt_percent"
              title="Cu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="As_wt_percent"
              title="As (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Zr_wt_percent"
              title="Zr (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Nb_wt_percent"
              title="Nb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Mo_wt_percent"
              title="Mo (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ru_wt_percent"
              title="Ru (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Rh_wt_percent"
              title="Rh (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pd_wt_percent"
              title="Pd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Cd_wt_percent"
              title="Cd (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sn_wt_percent"
              title="Sn (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sb_wt_percent"
              title="Sb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Te_wt_percent"
              title="Te (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="La_wt_percent"
              title="La (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ce_wt_percent"
              title="Ce (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pm_wt_percent"
              title="Pm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Sm_wt_percent"
              title="Sm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Eu_wt_percent"
              title="Eu (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Dy_wt_percent"
              title="Dy (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tm_wt_percent"
              title="Tm (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Yb_wt_percent"
              title="Yb (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ta_wt_percent"
              title="Ta (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Tl_wt_percent"
              title="Tl (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ra_wt_percent"
              title="Ra (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Ac_wt_percent"
              title="Ac (重量百分比)"
              width="120">
            </ux-table-column>
            <ux-table-column
              align="center"
              field="Pa_wt_percent"
              title="Pa (重量百分比)"
              width="120">
            </ux-table-column>
          </ux-grid>
        </el-card>
      </el-main>
    </el-container>
    <!--  ------------------------------统计和生成word按钮  -->
    <el-container>
      <el-header
        style="height: 50px">
        <div v-loading.fullscreen.lock="fullscreenLoading"
             element-loading-text="数据统计中..."
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.7)">
          <el-dialog
            title="提示"
            v-loading="loading"
            :visible.sync="dialogVisible"
            width="40%"
            :before-close="handleClose">
            <span>请选择生成的数据</span>
            <div>
              <el-checkbox v-model="checked1" :disabled="disabled1" label="夹杂物尺寸类型分布表" border></el-checkbox>
              <el-checkbox v-model="checked2" :disabled="disabled2" label="夹杂物尺寸类型分布图" border></el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="checked3" :disabled="disabled3" label="夹杂物尺寸数密度对比表" border></el-checkbox>
              <el-checkbox v-model="checked4" :disabled="disabled4" label="夹杂物尺寸数密度对比图" border></el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="checked7" :disabled="disabled7" label="夹杂物类型数密度表" border></el-checkbox>
              <el-checkbox v-model="checked8" :disabled="disabled8" label="夹杂物类型数密度图" border></el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="checked9" :disabled="disabled9" label="夹杂物平均成分对比表" border></el-checkbox>
              <el-checkbox v-model="checked10" :disabled="disabled10" label="夹杂物平均成分对比图" border></el-checkbox>
            </div>
            <div>
              <el-checkbox v-model="checked11" :disabled="disabled11" label="夹杂物尺寸分布对比表" border></el-checkbox>
              <el-checkbox v-model="checked12" :disabled="disabled12" label="夹杂物尺寸分布对比图" border></el-checkbox>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="genWord">确 定</el-button>
              </span>
          </el-dialog>
          <el-button
            type="primary"
            icon="el-icon-s-data"
            @click="statistic">
            统计
          </el-button>
          <el-button
            type="success"
            icon="el-icon-s-order"
            @click="genWordView">
            生成Word报告
          </el-button>
        </div>
      </el-header>
      <!--  ------------------------------图一表格控件  -->
      <!-- 第一个表格 -->
      <el-container>
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData1" style="width: 100%; overflow: visible;"
                      :highlight-current-row="true" :height="tableHeight" :fit="true" align="left"
                      @row-click="htTableClick">
              <!-- 固定列 -->
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="100"></el-table-column>
              <el-table-column align="center" prop="analysis_area" label="分析面积(mm2)" width="120"></el-table-column>
              <!-- 动态列 -->
              <el-table-column v-for="col in dynamicColumns1" :key="col" align="center" :prop="col" :label="col"
                              width="120"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>
      <!--  ------------------------------图二表格控件  -->
      <el-container>
        <el-aside width="900px" style="background-color: #FFFFFF; padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData2" style="width: 100%" height="580px" align="center"
                      @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" prop="a" fixed></el-table-column>
              <el-table-column align="center" prop="index" label="顺序" width="70" fixed></el-table-column>
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="150"></el-table-column>
              <el-table-column align="center" prop="analysis_area" label="分析面积(mm2)" width="120"></el-table-column>
              <el-table-column align="center" prop="inclusions_avg_size" label="夹杂物平均尺寸"
                               width="150"></el-table-column>
              <el-table-column align="center" prop="inclusions_num" label="夹杂物数密度" width="150"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart1" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>
      <!--  ------------------------------图三表格控件  -->
      <el-container>
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <!-- 调试信息 -->
            <!-- <div>动态列: {{ dynamicColumns }}</div>  -->
            <el-table border stripe :data="htTableData3" style="width: 100%; overflow: visible;"
                      :highlight-current-row="true" :height="tableHeight" :fit="true" align="left"
                      @row-click="htTableClick1">
              <!-- 固定列 -->
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="100"></el-table-column>
              <el-table-column align="center" prop="analysis_area" label="分析面积(mm2)" width="120"></el-table-column>
              <!-- 动态列 -->
              <el-table-column v-for="col in dynamicColumns" :key="col" align="center" :prop="col" :label="col"
                               width="240"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart2" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>
      <!--  ------------------------------图四表格控件  -->
      <el-container>
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData6" style="width: 100%" :highlight-current-row="true"
                      height="580px" align="center" @selection-change="handleSelectionChange6">
              <el-table-column align="center" type="selection" prop="a" fixed></el-table-column>
              <el-table-column align="center" prop="index" label="顺序" width="70" fixed></el-table-column>
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="100"></el-table-column>
              <el-table-column align="center" prop="N_wt_percent" label="N含量" width="100"></el-table-column>
              <el-table-column align="center" prop="O_wt_percent" label="O含量" width="100"></el-table-column>
              <el-table-column align="center" prop="F_wt_percent" label="F含量" width="100"></el-table-column>
              <el-table-column align="center" prop="S_wt_percent" label="S含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Ce_wt_percent" label="Ce含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Ca_wt_percent" label="Ca含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Mg_wt_percent" label="Mg含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Al_wt_percent" label="Al含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Ti_wt_percent" label="Ti含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Si_wt_percent" label="Si含量" width="100"></el-table-column>
              <el-table-column align="center" prop="Mn_wt_percent" label="Mn含量" width="120"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart6" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>

      <!--  ------------------------------图五表格控件  -->
      <el-container>
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData7" style="width: 100%" :highlight-current-row="true"
                      height="580px" align="center" @selection-change="handleSelectionChange7" @row-click="handleRowClick7">
              <el-table-column align="center" type="selection" prop="a" fixed></el-table-column>
              <el-table-column align="center" prop="index" label="顺序" width="70" fixed></el-table-column>
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="150"></el-table-column>
              <el-table-column align="center" prop="analysis_area" label="分析面积(mm2)" width="120"></el-table-column>
              <el-table-column align="center" prop="inclusions_size_0-2μm" label="0~2μm" width="150"></el-table-column>
              <el-table-column align="center" prop="inclusions_size_2-5μm" label="2~5μm" width="150"></el-table-column>
              <el-table-column align="center" prop="inclusions_size_5-10μm" label="5~10μm"
                               width="150"></el-table-column>
              <el-table-column align="center" prop="inclusions_size_10+μm" label=">10μm" width="150"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart7" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>      
      
      <!--  ------------------------------图六表格控件  -->
      <el-container style="margin-top: 20px;">
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData8" style="width: 100%" :highlight-current-row="true"
                      height="580px" align="center" @selection-change="handleSelectionChange8" @row-click="htTableClick8">
              <el-table-column align="center" type="selection" prop="a" fixed></el-table-column>
              <el-table-column align="center" prop="index" label="顺序" width="70" fixed></el-table-column>
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="150"></el-table-column>
              <el-table-column align="center" prop="min_diameter" label="最小直径(μm)" width="120"></el-table-column>
              <el-table-column align="center" prop="max_diameter" label="最大直径(μm)" width="120"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart8" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>

      <!--  ------------------------------图七表格控件  -->
      <el-container style="margin-top: 20px;">
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData9" style="width: 100%" 
                      :highlight-current-row="true" height="580px" align="center" 
                      @selection-change="handleSelectionChange9">
              
              <!-- 🔴 添加多选框列 -->
              <el-table-column 
                align="center" 
                type="selection" 
                fixed 
                width="55">
              </el-table-column>
              
              <el-table-column align="center" prop="selectionOrder"  label="顺序"  width="70"></el-table-column>
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" prop="SNUMB" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="150"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="180"></el-table-column>
              
              <el-table-column align="center" label="图1数据点" width="150">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.chart1_count > 0" type="success">
                    {{ scope.row.chart1_count }} 个点
                  </el-tag>
                  <el-tag v-else type="info">无数据</el-tag>
                </template>
              </el-table-column>
              
              <el-table-column align="center" label="图2数据点" width="150">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.chart2_count > 0" type="warning">
                    {{ scope.row.chart2_count }} 个点
                  </el-tag>
                  <el-tag v-else type="info">无数据</el-tag>
                </template>
              </el-table-column>
              
            </el-table>
          </el-card>
        </el-aside>
        
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div style="display: flex; height: 580px;">
              <div ref="chart9" style="width: 50%; height: 100%; border-right: 1px solid #e4e7ed;"></div>
              <div ref="chart10" style="width: 50%; height: 100%;"></div>
            </div>
          </el-card>
        </el-main>
      </el-container>

      <!--  ------------------------------图八表格控件  -->
      <el-container style="margin-top: 20px;">
        <el-aside width="900px" style="background-color: #FFFFFF;padding: 0; margin-right: 20px">
          <el-card style="height: 620px" v-loading="htLoading">
            <el-table border stripe :data="htTableData10" style="width: 100%" :highlight-current-row="true"
                      height="580px" align="center" @selection-change="handleSelectionChange10" @row-click="htTableClick10">
              <!--<el-table-column align="center" type="selection" prop="a" fixed></el-table-column>   -->
              <!--<el-table-column align="center" prop="index" label="顺序" width="70" fixed></el-table-column>-->
              <el-table-column align="center" prop="DT" label="时间" width="180"></el-table-column>
              <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
              <el-table-column align="center" prop="excel_name" label="文件名" width="120"></el-table-column>
              <el-table-column align="center" prop="section" label="样品" width="150"></el-table-column>
              <el-table-column align="center" prop="bubble_lt2" label="<2μm" width="100"></el-table-column>
              <el-table-column align="center" prop="bubble_2to5" label="2~5μm" width="100"></el-table-column>
              <el-table-column align="center" prop="bubble_5to10" label="5~10μm" width="100"></el-table-column>
              <el-table-column align="center" prop="bubble_gt10" label=">10μm" width="100"></el-table-column>
            </el-table>
          </el-card>
        </el-aside>
        <el-main style="padding: 0">
          <el-card style="height: 620px">
            <div ref="chart11" style="width: 100% ;height: 580px ">
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>


<script>
import * as echarts from 'echarts';
import service from "@/utils/request";
import {removeWatermark, setWaterMark} from '@/views/watermark'
import * as XLSX from 'xlsx';
import {saveAs} from 'file-saver';

export default {
  name: "Index",
  mounted() {
    this.initData();
    this.remoteMethod({})
  },
  destroyed() {
    removeWatermark();
  },
  data() {
    return {
            // 版本号
      htLoading: false,
      version: "3.8.8",
      tabPosition: 'left',
      exportTable1: [],
      exportTable2: [],
      loading: false,  // 添加loading状态
      conditionChangeTimer: null,
      // 统一的筛选表单数据
      form: {
      pageSize: 20,
      currentPage: 1,
      syNumbers: [],
      dateOption: this.getDefaultDateRange(), // 设置默认两个月时间范围
      fileNames: [],
      options1: [],
      options2: [],
      currentPage2: 1,
      
      // 高级筛选条件
      sampleTypes: [],
      samplingPositions: [],
      samplingProcesses: [],
      chartNames: [],
      steelMarks: [],
      samplingTimeRange: [],
      submitters: [],
      remarks: '',
      
      // 所有选项数组 - 确保这些都被正确初始化
      sampleTypeOptions: [],
      samplingPositionOptions: [],
      samplingProcessOptions: [],
      chartNameOptions: [],
      steelMarkOptions: [],
      samplingTimeOptions: [],
      submitterOptions: []
      },
      // 优化的请求状态管理
      requestStatus: {
        pendingRequests: new Map(),
        lastRequestTime: new Map(),
        isInitialLoad: true,
        loadingFlags: new Map()
      },
      labelPosition: 'right',
      fileNames: [],
      tableData1: [],
      tableHeight: 0,
      tableData1Total: 0,
      table1PageSize: 20,
      tableData2: [],
      tableData2Total: 0,
      table2PageSize: 20,
      table2Condition: {
        syNumber: [],
        date: [],
        fileName: []
      },
      jzwTableData: [],
      jzwTableData2: [],
      dynamicColumns: [],
      dynamicColumns1: [],
      htTableData1: [],
      htTableData2: [],
      htTableData3: [],
      htTableData6: [],
      htTableData7: [],
      htTableData8: [],  // 图表6：双Y轴点线图数据
      htTableData9: [],  // 图表7：三元相图数据
      htTableData10: [], // 图表8：气泡颜色映射图数据
      selectedRows: [],
      selectIdList: [],
      selectedSamples: [],     // 选中的样品
      // 图表5循环切换相关属性
      currentChartType: 0, // 当前图表类型 (0-4)
      lastClickedRow: null, // 上次点击的行
      chart9: null,            // 三元相图图1的图表实例
      chart10: null,           // 三元相图图2的图表实例
      ht1Url: "",
      ht2Url: "",
      ht3Url: "",
      ht6Url: "",
      ht7Url: "",
      ht8Url: "",  // 图表6：双Y轴点线图URL
      ht9Url: "",  // 图表7：三元相图URL
      ht10Url: "", // 图表8：气泡颜色映射图URL
      dialogVisible: false,
      dialogVisible2: false,
      dcdialogVisible: false,
      checked1: false,
      checked2: false,
      checked3: false,
      checked4: false,
      checked5: false,
      checked6: false,
      checked7: false,
      checked8: false,
      checked9: false,
      checked10: false,
      checked11: false,
      checked12: false,
      loading: false,
      disabled1: true,
      disabled2: true,
      disabled3: true,
      disabled4: true,
      disabled5: true,
      disabled6: true,
      disabled7: true,
      disabled8: true,
      disabled9: true,
      disabled10: true,
      disabled11: true,
      disabled12: true,
      ht1CurRow: [],
      ht3CurRow: [],
      fullscreenLoading: false,
      searchParams: {},
      templateName: '',           // 模板名称
      showTemplateButtons: false  // 是否显示模板按钮
    };
  },
  async mounted() {
    // 页面加载时标记为初始加载
    this.requestStatus.isInitialLoad = true
    await this.loadAllConditionOptionsSequentially()
    this.requestStatus.isInitialLoad = false
  },
  //  定义方法     //
  methods: {
    // 优化的条件改变处理
    async onConditionChange() {
      // 如果是初始加载，不处理
      if (this.requestStatus.isInitialLoad) {
        return
      }
      
      // 防抖处理
      if (this.conditionChangeTimer) {
        clearTimeout(this.conditionChangeTimer)
      }
      
      // 取消之前的请求
      if (this.loadingController) {
        this.loadingController.abort()
      }
      
      this.conditionChangeTimer = setTimeout(async () => {
        console.log('条件改变，重新加载所有其他条件的选项')
        
        // 创建新的请求控制器
        this.loadingController = new AbortController()
        
        try {
          await this.loadAllConditionOptionsSequentially()
        } catch (error) {
          if (error.name !== 'AbortError') {
            console.error('加载条件选项失败:', error)
          }
        }
      }, 800) // 增加防抖时间
    },
    
    // 优化的focus处理 - 避免重复请求
    async handleFocus(field) {
      // 如果是初始加载阶段，不处理
      if (this.requestStatus.isInitialLoad) {
        console.log(`[${field}] 初始加载阶段，跳过focus处理`)
        return
      }
      
      // 检查是否已有数据
      const optionsMap = {
        'excel_name': 'options1',
        'section': 'options2',
        'sample_type': 'sampleTypeOptions',
        'sampling_location': 'samplingPositionOptions',
        'sampling_process': 'samplingProcessOptions',
        'chart_name': 'chartNameOptions',
        'casting_mark': 'steelMarkOptions',
        'sampling_time': 'samplingTimeOptions',
        'sample_sender': 'submitterOptions'
      }
      
      const optionsKey = optionsMap[field]
      if (optionsKey && this.form[optionsKey] && this.form[optionsKey].length > 0) {
        console.log(`[${field}] 选项已存在(${this.form[optionsKey].length}个)，跳过重新加载`)
        return
      }
      
      // 检查是否有正在进行的请求
      const requestKey = `focus_${field}`
      if (this.requestStatus.pendingRequests.has(requestKey)) {
        console.log(`[${field}] 请求正在进行，跳过`)
        return
      }
      
      // 检查最近请求时间，避免频繁请求
      const lastTime = this.requestStatus.lastRequestTime.get(requestKey)
      const now = Date.now()
      if (lastTime && (now - lastTime) < 1000) {
        console.log(`[${field}] 请求过于频繁，跳过`)
        return
      }
      
      // 记录请求时间
      this.requestStatus.lastRequestTime.set(requestKey, now)
      
      // 调用对应的加载方法
      const loadMethods = {
        'excel_name': this.loadFileNames,
        'section': this.loadSyNumbers,
        'sample_type': this.loadSampleTypes,
        'sampling_location': this.loadSamplingPositions,
        'sampling_process': this.loadSamplingProcesses,
        'chart_name': this.loadChartNames,
        'casting_mark': this.loadSteelMarks,
        'sampling_time': this.loadSamplingTimes,
        'sample_sender': this.loadSubmitters
      }
      
      const loadMethod = loadMethods[field]
      if (loadMethod) {
        try {
          await loadMethod()
        } catch (error) {
          console.error(`[${field}] focus加载失败:`, error)
        }
      }
    },
    
    // 串行加载所有条件选项
    async loadAllConditionOptionsSequentially() {
      const loadTasks = [
        { name: '文件名', method: this.loadFileNames, key: 'fileNames' },
        { name: '试样号', method: this.loadSyNumbers, key: 'syNumbers' },
        { name: '试样类型', method: this.loadSampleTypes, key: 'sampleTypes' },
        { name: '取样位置', method: this.loadSamplingPositions, key: 'samplingPositions' },
        { name: '取样工序', method: this.loadSamplingProcesses, key: 'samplingProcesses' },
        { name: '作图名称', method: this.loadChartNames, key: 'chartNames' },
        { name: '出钢记号', method: this.loadSteelMarks, key: 'steelMarks' },
        { name: '取样时间', method: this.loadSamplingTimes, key: 'samplingTimes' },
        { name: '送样人', method: this.loadSubmitters, key: 'submitters' }
      ]
      
      // 串行执行，每个请求间隔200ms
      for (const task of loadTasks) {
        if (this.loadingController && this.loadingController.signal.aborted) {
          break
        }
        
        try {
          await task.method()
          // 适当间隔，避免请求过于密集
          await new Promise(resolve => setTimeout(resolve, 200))
        } catch (error) {
          if (error.message && error.message.includes('请勿重复提交')) {
            console.warn(`${task.name} 请求被拦截，跳过`)
            continue
          }
          if (error.name !== 'AbortError') {
            console.error(`${task.name} 加载失败:`, error)
          }
        }
      }
      
      console.log('所有条件选项加载完成')
    },
    
    // 优化的请求执行器
    async executeRequest(requestKey, apiCall) {
      // 检查是否已有相同请求在进行
      if (this.requestStatus.pendingRequests.has(requestKey)) {
        console.log(`[${requestKey}] 请求正在进行，跳过`)
        return null
      }
      
      // 检查加载标志
      if (this.requestStatus.loadingFlags.has(requestKey)) {
        console.log(`[${requestKey}] 加载标志已设置，跳过`)
        return null
      }
      
      try {
        // 标记请求开始
        this.requestStatus.pendingRequests.set(requestKey, true)
        this.requestStatus.loadingFlags.set(requestKey, true)
        
        // 执行API调用
        const result = await apiCall()
        
        return result
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn(`[${requestKey}] 请求被拦截，这是正常的`)
          return null
        }
        throw error
      } finally {
        // 清除标记
        this.requestStatus.pendingRequests.delete(requestKey)
        // 延迟清除加载标志，避免过快的重复请求
        setTimeout(() => {
          this.requestStatus.loadingFlags.delete(requestKey)
        }, 1000)
      }
    },

    async handleFileNameVisibleChange(visible) {
      if (visible && (!this.form.options1 || this.form.options1.length === 0)) {
        console.log('[文件名] 下拉框打开，开始加载选项')
        await this.loadFileNames()
      }
    },

    async handleSyNumberVisibleChange(visible) {
      if (visible && (!this.form.options2 || this.form.options2.length === 0)) {
        console.log('[试样号] 下拉框打开，开始加载选项')
        await this.loadSyNumbers()
      }
    },

    async handleSampleTypeVisibleChange(visible) {
      if (visible && (!this.form.sampleTypeOptions || this.form.sampleTypeOptions.length === 0)) {
        console.log('[试样类型] 下拉框打开，开始加载选项')
        await this.loadSampleTypes()
      }
    },

    async handleSamplingPositionVisibleChange(visible) {
      if (visible && (!this.form.samplingPositionOptions || this.form.samplingPositionOptions.length === 0)) {
        console.log('[取样位置] 下拉框打开，开始加载选项')
        await this.loadSamplingPositions()
      }
    },

    async handleSamplingProcessVisibleChange(visible) {
      if (visible && (!this.form.samplingProcessOptions || this.form.samplingProcessOptions.length === 0)) {
        console.log('[取样工序] 下拉框打开，开始加载选项')
        await this.loadSamplingProcesses()
      }
    },

    async handleChartNameVisibleChange(visible) {
      if (visible && (!this.form.chartNameOptions || this.form.chartNameOptions.length === 0)) {
        console.log('[作图名称] 下拉框打开，开始加载选项')
        await this.loadChartNames()
      }
    },

    async handleSteelMarkVisibleChange(visible) {
      if (visible && (!this.form.steelMarkOptions || this.form.steelMarkOptions.length === 0)) {
        console.log('[出钢记号] 下拉框打开，开始加载选项')
        await this.loadSteelMarks()
      }
    },

    async handleSamplingTimeVisibleChange(visible) {
      if (visible && (!this.form.samplingTimeOptions || this.form.samplingTimeOptions.length === 0)) {
        console.log('[取样时间] 下拉框打开，开始加载选项')
        await this.loadSamplingTimes()
      }
    },

    async handleSubmitterVisibleChange(visible) {
      if (visible && (!this.form.submitterOptions || this.form.submitterOptions.length === 0)) {
        console.log('[送样人] 下拉框打开，开始加载选项')
        await this.loadSubmitters()
      }
    },

    // 优化的加载方法 - 添加请求去重
    async loadFileNames() {
      const requestKey = 'loadFileNames'
      
      // 检查是否已有请求在进行
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[文件名] 请求正在进行，跳过')
        return
      }
      
      try {
        // 标记请求开始
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('excel_name')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'excel_name',
          conditions: conditions
        })
        
        if (res && res.nameList) {
          this.form.options1 = res.nameList
          console.log(`[文件名] 加载了 ${res.nameList.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[文件名] 请求被拦截，跳过')
          return
        }
        console.error('加载文件名失败:', error)
      } finally {
        // 清除请求标记
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSyNumbers() {
      const requestKey = 'loadSyNumbers'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[试样号] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('section')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'section',
          conditions: conditions
        })
        
        if (res && res.nameList) {
          this.form.options2 = res.nameList
          console.log(`[试样号] 加载了 ${res.nameList.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[试样号] 请求被拦截，跳过')
          return
        }
        console.error('加载试样号失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSampleTypes() {
      const requestKey = 'loadSampleTypes'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[试样类型] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('sample_type')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'sample_type',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.sampleTypeOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[试样类型] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[试样类型] 请求被拦截，跳过')
          return
        }
        console.error('加载试样类型失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSamplingPositions() {
      const requestKey = 'loadSamplingPositions'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[取样位置] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('sampling_location')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'sampling_location',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.samplingPositionOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[取样位置] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[取样位置] 请求被拦截，跳过')
          return
        }
        console.error('加载取样位置失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSamplingProcesses() {
      const requestKey = 'loadSamplingProcesses'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[取样工序] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('sampling_process')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'sampling_process',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.samplingProcessOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[取样工序] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[取样工序] 请求被拦截，跳过')
          return
        }
        console.error('加载取样工序失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadChartNames() {
      const requestKey = 'loadChartNames'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[作图名称] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('chart_name')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'chart_name',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.chartNameOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[作图名称] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[作图名称] 请求被拦截，跳过')
          return
        }
        console.error('加载作图名称失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSteelMarks() {
      const requestKey = 'loadSteelMarks'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[出钢记号] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('casting_mark')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'casting_mark',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.steelMarkOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[出钢记号] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[出钢记号] 请求被拦截，跳过')
          return
        }
        console.error('加载出钢记号失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSamplingTimes() {
      const requestKey = 'loadSamplingTimes'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[取样时间] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('sampling_time')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'sampling_time',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.samplingTimeOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[取样时间] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[取样时间] 请求被拦截，跳过')
          return
        }
        console.error('加载取样时间失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    async loadSubmitters() {
      const requestKey = 'loadSubmitters'
      
      if (this.requestStatus && this.requestStatus.pendingRequests.has(requestKey)) {
        console.log('[送样人] 请求正在进行，跳过')
        return
      }
      
      try {
        if (!this.requestStatus) {
          this.requestStatus = { pendingRequests: new Map() }
        }
        this.requestStatus.pendingRequests.set(requestKey, true)
        
        const conditions = this.getCurrentConditions('sample_sender')
        const res = await service.post('getAdvancedFilterOptions', {
          field: 'sample_sender',
          conditions: conditions
        })
        
        if (res && res.data) {
          this.form.submitterOptions = res.data.map((item, index) => ({
            label: item,
            value: item
          }))
          console.log(`[送样人] 加载了 ${res.data.length} 个选项`)
        }
      } catch (error) {
        if (error.message && error.message.includes('请勿重复提交')) {
          console.warn('[送样人] 请求被拦截，跳过')
          return
        }
        console.error('加载送样人失败:', error)
      } finally {
        if (this.requestStatus) {
          this.requestStatus.pendingRequests.delete(requestKey)
        }
      }
    },

    
    getDefaultDateRange() {
      const end = new Date(); // 当前日期
      end.setDate(end.getDate() + 1); // 明天
      const start = new Date(end); // 复制明天的日期
      start.setMonth(start.getMonth() - 12); // 明天的前两个月
      return [start, end];
    },

    // 修改：日期改变时的处理 - 不再特殊处理，只是重新加载文件名
    async remoteMethod() {
      console.log('remoteMethod 被调用，日期条件:', this.form.dateOption);
      
      // 日期改变时，重新加载文件名选项（基于新的日期条件）
      await this.loadFileNames();
      
      // 清空文件名选择（因为可选的文件名可能已经改变）
      this.form.fileNames = [];
      
      // 清空试样号选择和选项
      this.form.syNumbers = [];
      this.form.options2 = [];
    },

    // 获取当前条件
    getCurrentConditions(excludeField = null) {
      const conditions = {}
      
      if (!this.form) return conditions
      
      // 1. 日期条件
      if (this.form.dateOption && this.form.dateOption.length === 12) {
        conditions.dateOption = this.form.dateOption
      }
      
      // 2-10. 其他条件
      const conditionMappings = [
        { field: 'excel_name', key: 'fileNames', value: this.form.fileNames },
        { field: 'section', key: 'syNumbers', value: this.form.syNumbers },
        { field: 'sample_type', key: 'sampleTypes', value: this.form.sampleTypes },
        { field: 'sampling_location', key: 'samplingPositions', value: this.form.samplingPositions },
        { field: 'sampling_process', key: 'samplingProcesses', value: this.form.samplingProcesses },
        { field: 'chart_name', key: 'chartNames', value: this.form.chartNames },
        { field: 'casting_mark', key: 'steelMarks', value: this.form.steelMarks },
        { field: 'sampling_time', key: 'samplingTimes', value: this.form.samplingTimes },
        { field: 'sample_sender', key: 'submitters', value: this.form.submitters }
      ]
      
      for (const mapping of conditionMappings) {
        if (excludeField !== mapping.field && mapping.value && mapping.value.length > 0) {
          conditions[mapping.key] = mapping.value
        }
      }
      
      // 11. 备注条件
      if (this.form.remarks && this.form.remarks.trim()) {
        conditions.remarks = this.form.remarks.trim()
      }
      
      return conditions
    },
    
    // 日期改变时的处理
    async remoteMethod() {
      console.log('日期条件改变:', this.form.dateOption)
      
      // 清空相关选择
      this.form.fileNames = []
      this.form.syNumbers = []
      
      // 清空请求状态
      this.requestStatus.pendingRequests.clear()
      this.requestStatus.loadingFlags.clear()
      
      // 触发条件改变
      await this.onConditionChange()
    },
    
    // 搜索数据
    async selectData() {
      try {
        const hasCondition = 
          (this.form.dateOption && this.form.dateOption.length === 12) ||
          (this.form.fileNames && this.form.fileNames.length > 0) ||
          (this.form.syNumbers && this.form.syNumbers.length > 0) ||
          (this.form.sampleTypes && this.form.sampleTypes.length > 0) ||
          (this.form.samplingPositions && this.form.samplingPositions.length > 0) ||
          (this.form.samplingProcesses && this.form.samplingProcesses.length > 0) ||
          (this.form.chartNames && this.form.chartNames.length > 0) ||
          (this.form.steelMarks && this.form.steelMarks.length > 0) ||
          (this.form.samplingTimes && this.form.samplingTimes.length > 0) ||
          (this.form.submitters && this.form.submitters.length > 0) ||
          (this.form.remarks && this.form.remarks.trim())

        if (!hasCondition) {
          this.$message.warning('请至少选择一个筛选条件')
          return
        }

        const searchParams = {
          syNumbers: this.form.syNumbers || [],
          dateOption: this.form.dateOption || [],
          fileNames: this.form.fileNames || [],
          currentPage: this.form.currentPage || 1,
          pageSize: this.form.pageSize || 10,
          
          advancedFilters: {
            sampleTypes: this.form.sampleTypes || [],
            samplingPositions: this.form.samplingPositions || [],
            samplingProcesses: this.form.samplingProcesses || [],
            chartNames: this.form.chartNames || [],
            steelMarks: this.form.steelMarks || [],
            samplingTimes: this.form.samplingTimes || [],
            submitters: this.form.submitters || [],
            remarks: this.form.remarks || ''
          }
        }

        this.loading = true
        const res = await service.post('selectTableData', searchParams)
        
        this.tableData1 = res.nameList || []
        this.tableData1Total = res.total || 0
        this.exportTable1 = res.nameList || []

        this.table2Condition.fileName = this.form.fileNames || []
        this.table2Condition.date = this.form.dateOption || []
        this.table2Condition.syNumber = this.form.syNumbers || []

        this.$message.success(`搜索完成，共找到 ${res.total || 0} 条数据`)

      } catch (error) {
        console.error('搜索失败:', error)
        this.$message.error('搜索失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 清除搜索条件
    async clearSerch() {
      this.form = {
        pageSize: 20,
        currentPage: 1,
        syNumbers: [],
        dateOption: this.getDefaultDateRange(), // 默认俩月范围内
        fileNames: [],
        options1: [],
        options2: [],
        currentPage2: 1,
        sampleTypes: [],
        samplingPositions: [],
        samplingProcesses: [],
        chartNames: [],
        steelMarks: [],
        samplingTimes: [],
        submitters: [],
        remarks: '',
        sampleTypeOptions: [],
        samplingPositionOptions: [],
        samplingProcessOptions: [],
        chartNameOptions: [],
        steelMarkOptions: [],
        samplingTimeOptions: [],
        submitterOptions: []
      };
      
      // 重置表格数据
      this.tableData1 = [];
      this.tableData1Total = 0;
      
      this.$message.success('查询条件已清除');
    },
  

    
    // 导出
    exportTable() {
      if (this.checked6) {
        console.log('导出表2数据：', this.exportTable2)
        //遍历exportTable2，去掉_XID字段
        for (let i = 0; i < this.exportTable2.length; i++) {
          delete this.exportTable2[i]._XID
        }
        const headers = [
          {header: '时间', key: 'DT', width: 20},
          {header: '序号', key: 'SNUMB', width: 10},
          {header: '文件名', key: 'excel_name', width: 15},
          {header: '特征', key: 'IDNO', width: 10},
          {header: '区域', key: 'section', width: 15},
          {header: '夹杂物分类', key: 'inclusion_type', width: 15},
          {header: '视场', key: 'FOV', width: 10},
          {header: 'ECD((µm))', key: 'ECD', width: 15},
          {header: '面积(µm2)', key: 'area', width: 15},
          {header: '形状', key: 'shape', width: 15},
          {header: '长度(µm)', key: 'length', width: 15},
          {header: '周长(µm)', key: 'perimeter', width: 15},
          {header: '纵横比', key: 'aspect', width: 15},
          {header: '样品台X轴(mm)', key: 'X_axis', width: 20},
          {header: '样品台Y轴(mm)', key: 'Y_axis', width: 20},
          {header: '面积表文件名', key: 'excel2_name', width: 20},
          {header: 'PONO', key: 'PONO', width: 15},
          {header: '取样位置', key: 'sampling_location', width: 15},
          {header: '取样工序', key: 'sampling_process', width: 15},
          {header: '试样类型', key: 'sample_type', width: 15},
          {header: '分析面积(mm2)', key: 'analysis_area', width: 15},
          {header: '作图名称', key: 'chart_name', width: 15},
          {header: '出钢记号', key: 'casting_mark', width: 15},
          {header: '取样时间', key: 'sampling_time', width: 15},
          {header: '送样人', key: 'sample_sender', width: 15},
          {header: '备注', key: 'Remarks', width: 15},
          {header: 'Li (重量百分比)', key: 'Li_wt_percent', width: 15},
          {header: 'B (重量百分比)', key: 'B_wt_percent', width: 15},
          {header: 'C (重量百分比)', key: 'C_wt_percent', width: 15},
          {header: 'N (重量百分比)', key: 'N_wt_percent', width: 15},
          {header: 'O (重量百分比)', key: 'O_wt_percent', width: 15},
          {header: 'F (重量百分比)', key: 'F_wt_percent', width: 15},
          {header: 'Na (重量百分比)', key: 'Na_wt_percent', width: 15},
          {header: 'Mg (重量百分比)', key: 'Mg_wt_percent', width: 15},
          {header: 'Al (重量百分比)', key: 'Al_wt_percent', width: 15},
          {header: 'Si (重量百分比)', key: 'Si_wt_percent', width: 15},
          {header: 'P (重量百分比)', key: 'P_wt_percent', width: 15},
          {header: 'S (重量百分比)', key: 'S_wt_percent', width: 15},
          {header: 'Cl (重量百分比)', key: 'Cl_wt_percent', width: 15},
          {header: 'K (重量百分比)', key: 'K_wt_percent', width: 15},
          {header: 'Ca (重量百分比)', key: 'Ca_wt_percent', width: 15},
          {header: 'Ti (重量百分比)', key: 'Ti_wt_percent', width: 15},
          {header: 'V (重量百分比)', key: 'V_wt_percent', width: 15},
          {header: 'Cr (重量百分比)', key: 'Cr_wt_percent', width: 15},
          {header: 'Mn (重量百分比)', key: 'Mn_wt_percent', width: 15},
          {header: 'Fe (重量百分比)', key: 'Fe_wt_percent', width: 15},
          {header: 'Ni (重量百分比)', key: 'Ni_wt_percent', width: 15},
          {header: 'Cu (重量百分比)', key: 'Cu_wt_percent', width: 15},
          {header: 'As (重量百分比)', key: 'As_wt_percent', width: 15},
          {header: 'Zr (重量百分比)', key: 'Zr_wt_percent', width: 15},
          {header: 'Nb (重量百分比)', key: 'Nb_wt_percent', width: 15},
          {header: 'Mo (重量百分比)', key: 'Mo_wt_percent', width: 15},
          {header: 'Ru (重量百分比)', key: 'Ru_wt_percent', width: 15},
          {header: 'Rh (重量百分比)', key: 'Rh_wt_percent', width: 15},
          {header: 'Pd (重量百分比)', key: 'Pd_wt_percent', width: 15},
          {header: 'Cd (重量百分比)', key: 'Cd_wt_percent', width: 15},
          {header: 'Sn (重量百分比)', key: 'Sn_wt_percent', width: 15},
          {header: 'Sb (重量百分比)', key: 'Sb_wt_percent', width: 15},
          {header: 'Te (重量百分比)', key: 'Te_wt_percent', width: 15},
          {header: 'La (重量百分比)', key: 'La_wt_percent', width: 15},
          {header: 'Ce (重量百分比)', key: 'Ce_wt_percent', width: 15},
          {header: 'Pm (重量百分比)', key: 'Pm_wt_percent', width: 15},
          {header: 'Sm (重量百分比)', key: 'Sm_wt_percent', width: 15},
          {header: 'Eu (重量百分比)', key: 'Eu_wt_percent', width: 15},
          {header: 'Dy (重量百分比)', key: 'Dy_wt_percent', width: 15},
          {header: 'Tm (重量百分比)', key: 'Tm_wt_percent', width: 15},
          {header: 'Yb (重量百分比)', key: 'Yb_wt_percent', width: 15},
          {header: 'Ta (重量百分比)', key: 'Ta_wt_percent', width: 15},
          {header: 'Tl (重量百分比)', key: 'Tl_wt_percent', width: 15},
          {header: 'Ra (重量百分比)', key: 'Ra_wt_percent', width: 15},
          {header: 'Ac (重量百分比)', key: 'Ac_wt_percent', width: 15},
          {header: 'Pa (重量百分比)', key: 'Pa_wt_percent', width: 15},
        ];

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(this.exportTable2, {header: headers.map(h => h.key)});

        // 创建工作簿
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

        // 生成 Excel 文件并保存
        const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
        saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '表2.xlsx');
      }

      if (this.checked5) {
        service.post('exportExcel', this.form)
          .then(response => {
            console.log('Response:', response); // 打印整个响应对象
            console.log('list', response.resList)
            var table2List = response.resList
            const headers = [
              {header: '时间', key: 'DT', width: 20},
              {header: '序号', key: 'SNUMB', width: 10},
              {header: '文件名', key: 'excel_name', width: 15},
              {header: '特征', key: 'IDNO', width: 10},
              {header: '区域', key: 'section', width: 15},
              {header: '夹杂物分类', key: 'inclusion_type', width: 15},
              {header: '视场', key: 'FOV', width: 10},
              {header: 'ECD((µm))', key: 'ECD', width: 15},
              {header: '面积(µm2)', key: 'area', width: 15},
              {header: '形状', key: 'shape', width: 15},
              {header: '长度(µm)', key: 'length', width: 15},
              {header: '周长(µm)', key: 'perimeter', width: 15},
              {header: '纵横比', key: 'aspect', width: 15},
              {header: '样品台X轴(mm)', key: 'X_axis', width: 20},
              {header: '样品台Y轴(mm)', key: 'Y_axis', width: 20},
              {header: '面积表文件名', key: 'excel2_name', width: 20},
              {header: 'PONO', key: 'PONO', width: 15},
              {header: '取样位置', key: 'sampling_location', width: 15},
              {header: '取样工序', key: 'sampling_process', width: 15},
              {header: '试样类型', key: 'sample_type', width: 15},
              {header: '分析面积(mm2)', key: 'analysis_area', width: 15},
              {header: '作图名称', key: 'chart_name', width: 15},
              {header: '出钢记号', key: 'casting_mark', width: 15},
              {header: '取样时间', key: 'sampling_time', width: 15},
              {header: '送样人', key: 'sample_sender', width: 15},
              {header: '备注', key: 'Remarks', width: 15},
              {header: 'Li (重量百分比)', key: 'Li_wt_percent', width: 15},
              {header: 'B (重量百分比)', key: 'B_wt_percent', width: 15},
              {header: 'C (重量百分比)', key: 'C_wt_percent', width: 15},
              {header: 'N (重量百分比)', key: 'N_wt_percent', width: 15},
              {header: 'O (重量百分比)', key: 'O_wt_percent', width: 15},
              {header: 'F (重量百分比)', key: 'F_wt_percent', width: 15},
              {header: 'Na (重量百分比)', key: 'Na_wt_percent', width: 15},
              {header: 'Mg (重量百分比)', key: 'Mg_wt_percent', width: 15},
              {header: 'Al (重量百分比)', key: 'Al_wt_percent', width: 15},
              {header: 'Si (重量百分比)', key: 'Si_wt_percent', width: 15},
              {header: 'P (重量百分比)', key: 'P_wt_percent', width: 15},
              {header: 'S (重量百分比)', key: 'S_wt_percent', width: 15},
              {header: 'Cl (重量百分比)', key: 'Cl_wt_percent', width: 15},
              {header: 'K (重量百分比)', key: 'K_wt_percent', width: 15},
              {header: 'Ca (重量百分比)', key: 'Ca_wt_percent', width: 15},
              {header: 'Ti (重量百分比)', key: 'Ti_wt_percent', width: 15},
              {header: 'V (重量百分比)', key: 'V_wt_percent', width: 15},
              {header: 'Cr (重量百分比)', key: 'Cr_wt_percent', width: 15},
              {header: 'Mn (重量百分比)', key: 'Mn_wt_percent', width: 15},
              {header: 'Fe (重量百分比)', key: 'Fe_wt_percent', width: 15},
              {header: 'Ni (重量百分比)', key: 'Ni_wt_percent', width: 15},
              {header: 'Cu (重量百分比)', key: 'Cu_wt_percent', width: 15},
              {header: 'As (重量百分比)', key: 'As_wt_percent', width: 15},
              {header: 'Zr (重量百分比)', key: 'Zr_wt_percent', width: 15},
              {header: 'Nb (重量百分比)', key: 'Nb_wt_percent', width: 15},
              {header: 'Mo (重量百分比)', key: 'Mo_wt_percent', width: 15},
              {header: 'Ru (重量百分比)', key: 'Ru_wt_percent', width: 15},
              {header: 'Rh (重量百分比)', key: 'Rh_wt_percent', width: 15},
              {header: 'Pd (重量百分比)', key: 'Pd_wt_percent', width: 15},
              {header: 'Cd (重量百分比)', key: 'Cd_wt_percent', width: 15},
              {header: 'Sn (重量百分比)', key: 'Sn_wt_percent', width: 15},
              {header: 'Sb (重量百分比)', key: 'Sb_wt_percent', width: 15},
              {header: 'Te (重量百分比)', key: 'Te_wt_percent', width: 15},
              {header: 'La (重量百分比)', key: 'La_wt_percent', width: 15},
              {header: 'Ce (重量百分比)', key: 'Ce_wt_percent', width: 15},
              {header: 'Pm (重量百分比)', key: 'Pm_wt_percent', width: 15},
              {header: 'Sm (重量百分比)', key: 'Sm_wt_percent', width: 15},
              {header: 'Eu (重量百分比)', key: 'Eu_wt_percent', width: 15},
              {header: 'Dy (重量百分比)', key: 'Dy_wt_percent', width: 15},
              {header: 'Tm (重量百分比)', key: 'Tm_wt_percent', width: 15},
              {header: 'Yb (重量百分比)', key: 'Yb_wt_percent', width: 15},
              {header: 'Ta (重量百分比)', key: 'Ta_wt_percent', width: 15},
              {header: 'Tl (重量百分比)', key: 'Tl_wt_percent', width: 15},
              {header: 'Ra (重量百分比)', key: 'Ra_wt_percent', width: 15},
              {header: 'Ac (重量百分比)', key: 'Ac_wt_percent', width: 15},
              {header: 'Pa (重量百分比)', key: 'Pa_wt_percent', width: 15},
            ];

            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(table2List, {header: headers.map(h => h.key)});

            // 创建工作簿
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 生成 Excel 文件并保存
            const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '表1.xlsx');


          })
      }

    },

    //导出表1表2按钮
    daochu() {
      this.dcdialogVisible = true
      if (this.tableData1.length > 0) {
        this.disabled5 = false;
      }
      if (this.tableData2.length > 0) {
        this.disabled6 = false;
      }

    },
    //夹杂物自定义筛选按钮////////////////////////////////////////////////////////////////////////////////////////////////////
    JZWCustom() {
      // 检查是否有数据
      if (!this.tableData2 || this.tableData2.length === 0) {
        this.$message.error('没有可统计的数据');
        return;
      }

      // 使用 service 发送请求进行夹杂物分类统计
      service.post('/api/jzwfenlei', this.tableData2)
        .then(response => {
          console.log('夹杂物分类响应:', response);
          
          let resultData = [];
          if (Array.isArray(response)) {
            resultData = response;
          } else if (response && Array.isArray(response.data)) {
            resultData = response.data;
          }

          this.jzwTableData = resultData.map((item, index) => ({
            index: index + 1,
            jzwelement: item.jzwelement || '未知',
            jzwcount: item.jzwcount || 0,
            jzwType: item.jzwType || '',
            checked: item.checked || false
          }));

          console.log('处理后的 jzwTableData:', this.jzwTableData);

          if (this.jzwTableData.length === 0) {
            this.$message.warning('未统计出任何结果');
          } else {
            const hasTemplateData = this.jzwTableData.some(item => item.jzwType || item.checked);
            if (hasTemplateData) {
              this.$message.success('已自动加载上次使用的模板');
            }
          }

          // 🔥 显示模板按钮
          this.showTemplateButtons = true;
          
          // ❌ 删除这行：this.loadTemplateList();
          
          // 打开对话框
          this.dialogVisible2 = true;
        })
        .catch(error => {
          console.error('获取夹杂物分类数据失败:', error);
          this.$message.error('获取数据失败：' + (error.message || '未知错误'));
        });
    },
    
    // 🔥 保存模板
    saveTemplate() {
      this.$prompt('请输入模板名称', '保存模板', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '模板名称不能为空'
      }).then(({ value }) => {
        const templateData = {
          templateName: value,
          jzwTableData: this.jzwTableData
        };

        service.post('/api/jzw/template/save', templateData)
          .then(response => {
            console.log('保存模板响应:', response);
            
            if (response.success) {
              this.$message.success(response.message);
              
              // ❌ 删除这行：this.loadTemplateList();
              
              // 显示保存路径
              const templatePath = response.templatePath || response.data?.templatePath;
              if (templatePath) {
                this.$notify({
                  title: '模板保存成功',
                  message: `模板已保存到: ${templatePath}`,
                  type: 'success',
                  duration: 8000
                });
              }
            } else {
              this.$message.error(response.message);
            }
          })
          .catch(error => {
            console.error('保存模板失败:', error);
            this.$message.error('保存模板失败：' + (error.message || '未知错误'));
          });
      });
    },

    // 🔥 加载模板 - 修复界面刷新问题
    loadTemplate() {
      console.log('加载模板列表...');
      
      service.get('/api/jzw/template/list')
        .then(response => {
          if (response.success && response.templates.length > 0) {
            const templateList = response.templates;
            
            let templateHtml = '<div style="max-height: 300px; overflow-y: auto;">';
            templateList.forEach((template) => {
              const displayName = template.replace('.json', '');
              templateHtml += `
                <div style="padding: 10px; border: 1px solid #ddd; margin: 5px 0; cursor: pointer; border-radius: 4px; background: #f9f9f9; transition: background-color 0.2s;" 
                    onmouseover="this.style.backgroundColor='#e6f7ff'" 
                    onmouseout="this.style.backgroundColor='#f9f9f9'"
                    onclick="selectTemplate('${template}')">
                  <i class="el-icon-document"></i> ${displayName}
                </div>
              `;
            });
            templateHtml += '</div>';
            
            this.$msgbox({
              title: '选择模板',
              message: templateHtml,
              dangerouslyUseHTMLString: true,
              showCancelButton: true,
              confirmButtonText: '取消',
              cancelButtonText: '关闭',
              beforeClose: (action, instance, done) => {
                done();
              }
            });
            
            // 🔥 定义全局选择方法 - 修复界面刷新问题
            window.selectTemplate = (templateName) => {
              console.log('选择了模板:', templateName);
              
              // 关闭消息框
              this.$msgbox.close();
              
              // 加载选中的模板
              service.post('/api/jzw/template/load', { templateName: templateName })
                .then(response => {
                  if (response.success) {
                    // 🔥 应用模板数据并强制刷新
                    this.applyTemplateData(response.templateData);
                    
                    // 🔥 强制刷新视图
                    this.$nextTick(() => {
                      this.$forceUpdate();
                    });
                    
                    this.$message.success(`模板 "${templateName.replace('.json', '')}" 加载成功`);
                    
                    console.log('模板加载后的数据:', this.jzwTableData);
                  } else {
                    this.$message.error(response.message);
                  }
                })
                .catch(error => {
                  console.error('加载模板失败:', error);
                  this.$message.error('加载模板失败：' + (error.message || '未知错误'));
                });
            };
          } else {
            this.$message.warning('没有找到任何模板文件，请先保存一个模板');
          }
        })
        .catch(error => {
          console.error('获取模板列表失败:', error);
          this.$message.error('获取模板列表失败：' + (error.message || '未知错误'));
        });
    },

    // 🔥 应用模板数据 - 修复界面刷新问题
    applyTemplateData(templateData) {
      console.log('应用模板数据前:', JSON.parse(JSON.stringify(this.jzwTableData)));
      console.log('要应用的模板数据:', templateData);
      
      const templateMapping = {};
      
      // 创建映射表
      templateData.forEach(item => {
        templateMapping[item.jzwelement.toLowerCase()] = {
          jzwType: item.jzwType,
          checked: item.checked
        };
      });

      // 🔥 先清空所有数据，确保切换模板的正确性
      this.jzwTableData.forEach(item => {
        item.jzwType = '';
        item.checked = false;
      });

      // 🔥 应用到当前数据，使用 Vue.set 确保响应式更新
      this.jzwTableData.forEach((item, index) => {
        const key = item.jzwelement.toLowerCase();
        if (templateMapping[key]) {
          // 使用 Vue.set 确保响应式更新
          this.$set(item, 'jzwType', templateMapping[key].jzwType);
          this.$set(item, 'checked', templateMapping[key].checked);
        }
      });
      
      console.log('应用模板数据后:', JSON.parse(JSON.stringify(this.jzwTableData)));
    },
    // 夹杂物自定义分类确认选择  ///////////////////////////////////////////////////////////////////////////////////////////
    JZWconfirmselection() {
      // 过滤出选中的项
      const selectedItems = this.jzwTableData.filter(item => item.checked);

      // 如果没有选中任何项
      if (selectedItems.length === 0) {
        this.$message.warning('请至少选择一项');
        return;
      }

      // 提取选择的夹杂物类型
      const selectedTypes = selectedItems.map(item => item.jzwelement);

      // 发送请求到后端，插入数据
      service.post('/api/jzwfenleicharu', {
        selectedTypes: selectedTypes,
        tableData2: this.tableData2,
        jzwTableData: this.jzwTableData  // 传递整个 jzwTableData
      })
        .then(response => {
          console.log('后端返回的原始数据:', response);

          // 从返回的数据中获取 data 字段
          const filteredData = response.data;

          console.log('后端返回的数据:', filteredData);

          // 确保数据不为 undefined
          if (filteredData && filteredData.length > 0) {
            // 将筛选结果赋值给 jzwTableData2
            this.jzwTableData2 = filteredData;

            // 关闭对话框
            this.dialogVisible2 = false;
            this.$message.success(`成功筛选出 ${filteredData.length} 条数据`);
          } else {
            this.$message.warning('未获取到有效数据');
          }
        })
        .catch(error => {
          console.error('数据获取失败:', error);
          this.$message.error('数据插入失败：' + error.message);
        });
    },

    // 全选/全不选的双击事件处理
    handleHeaderDoubleClick() {
      // 检查是否有未选中的项
      const hasUnchecked = this.jzwTableData.some(item => !item.checked);

      // 检查是否所有项都已选中
      const allChecked = this.jzwTableData.every(item => item.checked);


      if (allChecked) {
        // 如果全部都已选中，则全部取消选中
        this.jzwTableData.forEach(item => {
          item.checked = false;
        });
      } else if (hasUnchecked) {
        // 如果有未选中的项，则全选
        this.jzwTableData.forEach(item => {
          item.checked = true;
        });
      }
    },

    // 辅助方法：获取更新后的 inclusion_type
    getUpdatedInclusionType(row, selectedTypes) {
      // 遍历选中的类型，找到匹配的并返回对应的用户编辑类型
      for (let selectedType of selectedTypes) {
        // 假设 row.inclusion_type 与 selectedType 匹配
        if (row.inclusion_type.toLowerCase() === selectedType.toLowerCase()) {
          // 找到对应的表格行并返回其 jzwType
          const matchedRow = this.jzwTableData.find(
            item => (item.jzwelement.toLowerCase() === selectedType.toLowerCase())
          );
          return matchedRow.jzwType || selectedType;
        }
      }
      return row.inclusion_type;
    },

    //生成word按钮
    genWordView() {
      this.dialogVisible = true
      if (this.htTableData1.length > 0) {
        this.disabled1 = false
      }
      if (this.htTableData2.length > 0) {
        this.disabled3 = false
      }
      if (!(this.ht1Url === '' || this.ht1Url === undefined || this.ht1Url === null)) {
        this.disabled2 = false
      }
      if (this.ht2Url && this.ht2Url !== '') {
        this.disabled4 = false
      }
      if (this.htTableData3.length > 0) {
        this.disabled7 = false
      }
      if (this.htTableData6.length > 0) {
        this.disabled9 = false
      }
      if (this.htTableData7.length > 0) {
        this.disabled11 = false
      }
      if (this.ht3Url && this.ht3Url !== '') {
        this.disabled8 = false
      }
      if (this.ht6Url && this.ht6Url !== '') {
        this.disabled10 = false
      }
      if (this.ht7Url && this.ht7Url !== '') {
        this.disabled12 = false
      }

    },
    //  生成word时关闭弹窗的控制
    handleClose() {
      this.dialogVisible = false
      this.checked1 = false
      this.checked2 = false
      this.checked3 = false
      this.checked4 = false
    },
    //  生成表1、2的excel时关闭弹窗的控制
    handleClose1() {
      this.dcdialogVisible = false
      this.checked5 = false
      this.checked6 = false
    },


    // 🔥统计（一键）
    async statistic() {
    if (this.tableData2.length === 0) {
      this.$message.error('表中无数据，无法统计！');
      return;
    }

    // 如果jzwTableData2为空，使用tableData2
    const dataToUse = this.jzwTableData2.length > 0 ? this.jzwTableData2 : this.tableData2;

    // 立即显示加载
    this.fullscreenLoading = true;

    try {
      // 串行发送请求，不会同时压垮浏览器和服务器
      const res = await service.post('statistic', dataToUse);
      this.htTableData1 = res.data;
      // 动态设置第一个表格的列
      if (res.columns) {
        // 过滤掉固定列，只保留动态列
        const fixedColumns = ['DT', 'SNUMB', 'excel_name', 'section', 'analysis_area'];
        this.dynamicColumns1 = res.columns.filter(col => !fixedColumns.includes(col));
      }

      const res2 = await service.post('statistic2', dataToUse);
      this.htTableData2 = res2.data;

      const res3 = await service.post('statistic3', dataToUse);
      this.htTableData3 = res3.data;

      // 动态设置列
      if (res3.columns) {
        this.dynamicColumns = res3.columns;
      }

      // 稍微调整表格高度
      this.tableHeight = 570; // 减小 10px 或其他微小调整  实属无奈之举，因为滚动条位置不这样调会一直位于card的中间位置
      this.$nextTick(() => {
        this.tableHeight = 580; // 恢复原始高度
        this.$forceUpdate(); // 强制重新渲染 el-table 组件
      });

      const res6 = await service.post('statistic6', dataToUse);
      this.htTableData6 = res6.data;

      const res7 = await service.post('statistic7', dataToUse);
      this.htTableData7 = res7.data;

      const res8 = await service.post('statistic8', dataToUse);
      this.htTableData8 = res8.data;

      // 🔴 图9：三元相图，只使用原始数据 tableData2（不考虑筛选）
      this.htLoading = true;
      const res9 = await service.post('statistic9', this.tableData2);
      this.htTableData9 = res9.data;

      console.log('三元相图统计结果:', this.htTableData9);
      console.log(`共 ${this.htTableData9.length} 个样品`);

      
      const res10 = await service.post('statistic10', dataToUse);
      this.htTableData10 = res10.data;

      this.$message.success('统计完成！');
      
    } catch (error) {
      console.error('统计错误:', error);
      
      // 优先显示后端返回的具体错误信息
      const errorMessage = error.response?.data?.error || '统计过程中发生错误';
      this.$message.error(errorMessage);
      // 添加自定义样式类
      this.$message({
        type: 'error',
        message: errorMessage,
        customClass: 'statistic-error-message'
      });
    } finally {
      // 无论成功或失败，都关闭加载状态
      this.fullscreenLoading = false;
      this.htLoading = false;
    }
  },

    // 生成Word报告
    genWord() {
      console.log(this.ht3Url)
      console.log(this.htTableData3)
      
      // 显示加载提示
      this.loading = true;

      // 动态生成列顺序的函数
      const getColumnOrder = (tableData, fixedColumns = []) => {
        if (!tableData || tableData.length === 0) return [];
        
        const dataKeys = Object.keys(tableData[0]);
        const dynamicColumns = dataKeys.filter(key => !fixedColumns.includes(key));
        
        // 固定列在前，动态列在后
        return [...fixedColumns, ...dynamicColumns];
      };

      // 定义固定的列顺序
      const fixedColumns = ['index', 'DT', 'SNUMB', 'excel_name', 'section', 'analysis_area'];

      // 准备传递给后端的数据
      const data = {
        htSteelNum: this.form.steelNumber,
        htTableData1: !this.checked1 ? [] : this.htTableData1,
        htTableData2: !this.checked3 ? [] : this.htTableData2,
        htTableData3: !this.checked7 ? [] : this.htTableData3,
        htTableData4: !this.checked9 ? [] : this.htTableData6,
        htTableData5: !this.checked11 ? [] : this.htTableData7,
        // 动态生成列顺序
        htTableColumns1: !this.checked1 ? [] : getColumnOrder(this.htTableData1, fixedColumns),
        htTableColumns2: !this.checked3 ? [] : [
          'index', 'DT', 'SNUMB', 'excel_name', 'section', 'analysis_area',
          'inclusions_num', 'inclusions_avg_size'
        ],
        htTableColumns3: !this.checked7 ? [] : getColumnOrder(this.htTableData3, fixedColumns),
        htTableColumns4: !this.checked9 ? [] : [
          'index', 'DT', 'SNUMB', 'excel_name', 'section', 'analysis_area',
          'Al_wt_percent', 'Ca_wt_percent', 'Ce_wt_percent', 'F_wt_percent',
          'Mg_wt_percent', 'Mn_wt_percent', 'N_wt_percent', 'O_wt_percent',
          'S_wt_percent', 'Si_wt_percent', 'Ti_wt_percent'
        ],
        htTableColumns5: !this.checked11 ? [] : [
          'index', 'DT', 'SNUMB', 'excel_name', 'section', 'analysis_area',
          'inclusions_size_0-2μm', 'inclusions_size_2-5μm', 'inclusions_size_5-10μm', 'inclusions_size_10+μm'
        ],
        ht1: !this.checked2 ? '' : this.ht1Url,
        ht2: !this.checked4 ? '' : this.ht2Url,
        ht3: !this.checked8 ? '' : this.ht3Url,
        ht4: !this.checked10 ? '' : this.ht6Url,
        ht5: !this.checked12 ? '' : this.ht7Url
      };

      // 调试：打印发送的列顺序数据
      console.log('htTableColumns1:', data.htTableColumns1)
      console.log('htTableColumns2:', data.htTableColumns2)
      console.log('htTableColumns3:', data.htTableColumns3)
      console.log('htTableColumns4:', data.htTableColumns4)
      console.log('htTableColumns5:', data.htTableColumns5)

      // 显示处理提示
      this.$message.info('正在生成Word文档，请稍候...');

      // 发送请求并处理响应
      service.post('/genWord', data, {
        responseType: 'blob',
        timeout: 600000, // 设置10分钟超时
        onDownloadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(`下载进度: ${percentCompleted}%`);
          }
        }
      }).then(response => {
        // 验证响应数据
        if (!response || response.size === 0) {
          throw new Error('服务器返回空文档');
        }

        console.log('Word文档生成成功, 大小:', response.size, 'bytes');

        // 创建下载链接
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });

        // 生成带时间戳的文件名
        const now = new Date();
        const timeStr = now.getFullYear() + 
                      (now.getMonth() + 1).toString().padStart(2, '0') +
                      now.getDate().toString().padStart(2, '0') + '_' +
                      now.getHours().toString().padStart(2, '0') +
                      now.getMinutes().toString().padStart(2, '0') +
                      now.getSeconds().toString().padStart(2, '0');
        const fileName = `质量分析报告_${timeStr}.docx`;

        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        link.style.display = 'none';
        
        document.body.appendChild(link);
        link.click();
        
        // 延迟清理资源，确保下载开始
        setTimeout(() => {
          if (document.body.contains(link)) {
            document.body.removeChild(link);
          }
          window.URL.revokeObjectURL(url);
        }, 100);

        // 显示成功消息
        this.$message.success('质量分析报告生成成功');

      }).catch(error => {
        console.error('生成Word文档失败:', error);
        
        // 详细的错误处理
        let errorMessage = '生成Word文档失败，请稍后重试';
        
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          errorMessage = '生成文档超时，数据量较大，请耐心等待或稍后重试';
        } else if (error.response) {
          const status = error.response.status;
          if (status === 400) {
            errorMessage = '请求数据格式错误，请检查数据';
          } else if (status === 500) {
            errorMessage = '服务器处理错误，请联系管理员';
          } else if (status === 502 || status === 503) {
            errorMessage = '服务器暂时不可用，请稍后重试';
          }
        } else if (error.request) {
          errorMessage = '网络连接失败，请检查网络连接';
        } else if (error.message === '服务器返回空文档') {
          errorMessage = '生成的文档为空，请检查数据是否完整';
        }
        
        this.$message.error(errorMessage);
        
      }).finally(() => {
        // 确保loading状态正确关闭
        this.loading = false;
      });
    },

    /* filterLowMaterial(){
      if(this.tableData1.length > 0){
        service.post('filterLowMaterial',this.table2Condition).then(res=>{
          this.tableData2 = res.data
          this.exportTable2 = res.data
          this.tableData2Total = res.total
        })
      }else{
        this.$message.error('请先查询上表');
      }
    }, */
    filterLowC() {
      if (this.tableData1.length > 0) {
        service.post('filterLowC', this.table2Condition).then(res => {
          this.tableData2 = res.data
          this.exportTable2 = res.data
          this.tableData2Total = res.total
        })
      } else {
        this.$message.error('请先查询上表');
      }
    },
    /* filterSi(){
      if(this.tableData1.length > 0){
        service.post('filterSi',this.table2Condition).then(res=>{
          this.tableData2 = res.data
          this.exportTable2 = res.data
          this.tableData2Total = res.total
        })
      }else{
        this.$message.error('请先查询上表');
      }
    },  */

    table2CurrentChange(a) {

    },

    table1CurrentChange(a) {
      this.form.currentPage = a;
      this.form.pageSize = this.table1PageSize;
      service.post('selectTableData', this.form).then(res => {
        this.tableData1 = res.nameList
        this.tableData1Total = res.total
      })
    },
    /*
    remoteMethodSyNumbers(query) {
      service.post('getSyNumbers', this.form).then(res => {
        this.form.options2 = res.nameList
      })
    },
    remoteMethod(query) {
      service.post('getFileList', {query})
        .then(res => {
          this.form.options1 = res.nameList
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.form.options1 = [];
        });
      this.form.options2 = [];
    }, */

    initData() {
      let str1 = "宝钢非金属夹杂物智能分析平台";
      //let str2 = sessionStorage.getItem('')
      setWaterMark(str1, '');
    },


    // <!-----------------------------------------图一表点击事件-------------------------------------------------------------------------->
    htTableClick(row, column, event) {
      console.log(row)
      service.post('statisticBar1', row).then(res => {
        this.initEcharts1(res.data)
        this.ht1CurRow = [row]
      })
    },

    // <!-----------------------------------------图一初始化------------------------------------------------------------------------------>
    initEcharts1(series) {
      // 检查并销毁已存在的图表实例
      const chartDom = this.$refs.chart;
      if (!chartDom) {
        console.error('找不到图表容器');
        return;
      }

      // 获取已存在的实例
      let chart = echarts.getInstanceByDom(chartDom);
      
      // 如果存在实例，先销毁
      if (chart) {
        chart.dispose();
      }

      // 重新初始化图表
      chart = echarts.init(chartDom, null, {
        devicePixelRatio: window.devicePixelRatio || 2.5, // 自动检测设备像素比
        renderer: 'canvas', // 使用canvas渲染器，通常比SVG更清晰
      });

      
      // 从series中提取legend数据
      const legendData = series.map(item => item.name || '');

      // **新增：动态计算Y轴最大值**
      let maxStackValue = 0;
      const categories = ['<2μm', '2-5μm', '5-10μm', '>10μm']; // X轴类别

      // 对每个X轴类别，计算所有series的累加值
      categories.forEach((category, categoryIndex) => {
        let stackSum = 0;
        
        // 遍历所有series，累加同一类别下的数据
        series.forEach(seriesItem => {
          if (seriesItem.data && seriesItem.data[categoryIndex] !== undefined) {
            const value = typeof seriesItem.data[categoryIndex] === 'object' 
              ? (seriesItem.data[categoryIndex].value || 0)
              : (parseFloat(seriesItem.data[categoryIndex]) || 0);
            stackSum += value;
          }
        });
        
        // 找到最大的堆叠值
        if (stackSum > maxStackValue) {
          maxStackValue = stackSum;
        }
      });

      // 计算Y轴最大值（最大堆叠值的1.2倍，至少为1）
      const yAxisMax = Math.max(Math.ceil(maxStackValue * 1.2), 1);

      console.log('堆叠数据最大值:', maxStackValue);
      console.log('Y轴设置最大值:', yAxisMax);
      
      var option;
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            // 只显示非0值
            let result = params[0].axisValue + '<br/>';
            params.forEach(function(item) {
              if (item.value !== 0 && item.value !== undefined) {
                result += item.marker + item.seriesName + ': ' + item.value + '<br/>';
              }
            });
            return result;
          }
        },
        // 图例配置
        legend: {
          orient: 'vertical',
          right: '10%', 
          top: '10%',   
          itemGap: 8,
          data: legendData,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman', // **新增：保持字体一致性**
            color: '#333',
            rich: {
              // 使用富文本，hover时显示完整信息
              full: {
                fontSize: 16,
                color: '#333',
                fontWeight: 'bold'
              }
            }
          },
          backgroundColor: 'rgba(255,255,255,0.85)',  // 半透明背景
          borderColor: 'rgba(200,200,200,0.5)',
          borderWidth: 1,
          borderRadius: 4,
           padding: [10, 12, 10, 12],  // **修改：稍微增大内边距以适应更大的字体**
          inactiveColor: 'rgba(0,0,0,0.25)',  // 非激活状态颜色（半透明）
          formatter: function(name) {
            // 如果图例太多，截断显示，hover时tooltip会显示完整信息
            return name.length > 12 ? name.substring(0, 12) + '...' : name;
          }
        },
        grid: {
          top: '12%',    // 向上移动（从15%改为8%）
          left: '20%',  // 向右移动（从3%改为20%，约200px）
          right: '25%',  // 为右侧图例留出空间
          bottom: '12%',  // 增加底部空间以显示x轴标题
          containLabel: true,
          width: 'auto',
          // 添加边框
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['<2μm', '2-5μm', '5-10μm', '>10μm'],
            name: '夹杂物尺寸(μm)',
            nameLocation: 'middle',
            nameGap: 50,  // 增大与轴的距离
            axisTick: {
              show: false  // 不显示x轴刻度线
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            axisLabel: {
              fontSize: 16,
              fontWeight: 'bold', // 字体变粗
              color: '#2e2d2d',
              fontFamily: 'Times New Roman'
            },
            nameTextStyle: {
              padding: [5, 0, 0, 0],  // 增加上边距
              color: '#2e2d2d',
              fontSize: 24,  // 调整为24
              fontWeight: 'bold', // 字体变粗
              fontFamily: 'Times New Roman',
            },
          }
        ],
        yAxis: [
          {
            name: '夹杂物数密度(个/mm²)',
            nameLocation: 'middle',
            type: 'value',
            nameRotate: 90, // 标题旋转角度
            nameGap: 50,
            position: 'left',  // 明确指定位置
            offset: 0,         // 轴的偏移量
            max: yAxisMax,  // **新增：设置动态计算的最大值**
            // 添加这个配置来控制水平网格线           
            axisTick: {
              show: true,
              inside: true  // y轴刻度线向内
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            nameTextStyle: {
              align: 'center',
              padding: [0, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,  // 调整为24
              fontWeight: 'bold', // 字体变粗
              fontFamily: 'Times New Roman',
            },
            axisLabel: {
              fontSize: 16,  // 增大30%: 12 * 1.3 = 15.6
              fontWeight: 'bold', // 字体变粗
              color: '#2e2d2d',
              fontFamily: 'Times New Roman'
            }
          }
        ],
        series: series
      };
      
      option && chart.setOption(option);
      
      // 使用事件监听来实现图例hover效果
      chart.on('mouseover', 'legend', function() {
        // hover图例时，可以显示完整信息
        console.log('hover图例');
      });
      
      // 移除之前的resize监听器（如果存在）
      if (this.chart1ResizeHandler) {
        window.removeEventListener('resize', this.chart1ResizeHandler);
      }
      
      // 创建新的resize监听器
      this.chart1ResizeHandler = () => {
        if (chart && !chart.isDisposed()) {
          chart.resize();
        }
      };
      
      window.addEventListener('resize', this.chart1ResizeHandler);

      // 保存图表实例引用
      this.chart1Instance = chart;

      // 组件销毁时移除监听和销毁图表
      this.$once('hook:beforeDestroy', () => {
        if (this.chart1ResizeHandler) {
          window.removeEventListener('resize', this.chart1ResizeHandler);
        }
        if (chart && !chart.isDisposed()) {
          chart.dispose();
        }
      });

      // 使用 setTimeout 确保图表已经完全渲染
      setTimeout(() => {
        if (chart && !chart.isDisposed()) {
          this.ht1Url = chart.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff',
          });
        }
      }, 1000); // 延迟 1 秒
    },


    // <!-----------------------------------------图二表点击事件-------------------------------------------------------------------------->
    handleSelectionChange(val) {
      this.htTableData2.forEach((el) => {
        this.$set(el, 'index', "");
      });
      val.forEach((i, idx) => {
        this.htTableData2.forEach((el) => {
          if (i.SNUMB == el.SNUMB) {
            this.$set(el, 'index', idx + 1);
            this.$set(i, 'index', idx + 1);
          }
        });
      });
      this.selectIdList = val;

      //初始化统计图2
      this.initEcharts2(this.selectIdList)
    },
    // <!-----------------------------------------图二初始化------------------------------------------------------------------------------>
    initEcharts2(values) {
      //遍历所有样品名称
      var names = [];
      values.forEach((i) => {
        names.push(i.section);
      });
      var sizes = [];
      values.forEach((i) => {
        sizes.push(i.inclusions_avg_size);
      });
      var numbers = [];
      values.forEach((i) => {
        numbers.push(i.inclusions_num);
      });
      // **新增：动态计算两个Y轴的最大值**
      // 计算左侧Y轴（夹杂物尺寸）的最大值
      let maxSizeValue = 0;
      sizes.forEach(item => {
        const value = parseFloat(item) || 0;
        if (value > maxSizeValue) {
          maxSizeValue = value;
        }
      });
      const leftYAxisMax = Math.max(Math.ceil(maxSizeValue * 1.2), 1);

      // 计算右侧Y轴（夹杂物数密度）的最大值
      let maxNumberValue = 0;
      numbers.forEach(item => {
        const value = parseFloat(item) || 0;
        if (value > maxNumberValue) {
          maxNumberValue = value;
        }
      });
      const rightYAxisMax = Math.max(Math.ceil(maxNumberValue * 1.2), 1);

      console.log('夹杂物尺寸最大值:', maxSizeValue, '-> Y轴最大值:', leftYAxisMax);
      console.log('夹杂物数密度最大值:', maxNumberValue, '-> Y轴最大值:', rightYAxisMax);

      const chart = echarts.init(this.$refs.chart1);
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['夹杂物尺寸', '夹杂物数密度'],
          orient: 'vertical',
          right: '5%',
          top: '10%',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333'
          },
          backgroundColor: 'rgba(255,255,255,0.85)',
          borderColor: 'rgba(200,200,200,0.5)',
          borderWidth: 2,
          borderRadius: 4,
          padding: [10, 12, 10, 12]
        },
        grid: {
          left: '20%',  // 向右移动，避免左侧标题被遮盖
          right: '25%',  // 为右侧图例留出空间
          bottom: '12%',  // 为x轴标题留出空间
          top: '12%',
          containLabel: true,
          width: 'auto',
          // 添加边框
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },
        xAxis: [
          {
            type: 'category',
            data: names,
            axisTick: {
              show: false  // 不显示x轴刻度线
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            axisLabel: {
              fontSize: 16,
              fontWeight: 'bold', 
              color: '#2e2d2d',
              fontFamily: 'Times New Roman'
            },
            name: '分析位置', // 添加X轴标题
            nameLocation: 'middle', // 标题位置
            nameGap: 50, // 标题与轴线的距离
            nameTextStyle: {
              padding: [5, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,
              fontWeight: 'bold',
              fontFamily: 'Times New Roman'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '夹杂物尺寸(μm)',
            position: 'left',
            nameLocation: 'middle',
            nameRotate: 90, // 标题旋转角度
            nameGap: 50,
            offset: 0,         // 轴的偏移量
            max: leftYAxisMax,  // **新增：设置左侧Y轴动态最大值**
            axisTick: {
              show: true,
              inside: true  // y轴刻度线向内
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: true  // 不显示横线
            },
            nameTextStyle: {
              align: 'center',
              padding: [0, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,
              fontWeight: 'bold',
              fontFamily: 'Times New Roman',
            },
            axisLabel: {
              fontSize: 16,  
              fontWeight: 'bold',
              color: '#2e2d2d',
              fontFamily: 'Times New Roman',
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '夹杂物数密度(个/mm²)',
            position: 'right',
            nameLocation: 'middle',
            nameRotate: 90, // 标题旋转角度
            nameGap: 50,
            offset: 0,         // 轴的偏移量
            max: rightYAxisMax,  // **新增：设置右侧Y轴动态最大值**
            axisTick: {
              show: true,
              inside: true  // y轴刻度线向内
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: false  // 不显示横线
            },
            nameTextStyle: {
              align: 'center',
              padding: [0, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,
              fontWeight: 'bold',
              fontFamily: 'Times New Roman',
            },
            axisLabel: {
              fontSize: 16,  
              fontWeight: 'bold',
              color: '#2e2d2d',
              fontFamily: 'Times New Roman',
              formatter: '{value}'
            }
          }
        ],
        
        // 🔴 关键：控制柱子位置和间距
        //barCategoryGap: '0%',  // 柱子间距设为 0
        //barGap: '20%',        // 同一类别内柱子间距设为 20%
        
        series: [
          {
            name: '夹杂物尺寸',
            type: 'bar',
            yAxisIndex: 0,
            data: sizes,
            barGap: '0%',  // 🔴 关键：设置为 0%，两个柱子紧贴
          },
          {
            name: '夹杂物数密度',
            type: 'bar',
            yAxisIndex: 1,
            data: numbers,
          }
        ]
      }
      option && chart.setOption(option);
      // 添加resize监听
      const resizeHandler = () => {
        chart.resize();
      };
      window.addEventListener('resize', resizeHandler);

      // 组件销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
      });

      // 使用 setTimeout 确保图表已经完全渲染
      setTimeout(() => {
        this.ht2Url = chart.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff',
        });
      }, 1000); // 延迟 1 秒
    },


    // <!-----------------------------------------图三表点击事件-------------------------------------------------------------------------->
    htTableClick1(row, column, event) {
      console.log('点击的行数据:', row);

      // 直接从行数据中提取图表所需信息
      const chartData = this.prepareChartData(row);

      // 使用提取的数据初始化图表
      this.initEcharts3(chartData);
      this.ht3CurRow = [row];
    },
    // <!-----------------------------------------图三数据准备---------------------------------------------------------------------------->
    prepareChartData(rowData) {
      // 存储夹杂物类型和对应的值
      const typesAndValues = [];

      // 需要排除的字段列表
      const excludeFields = ['SNUMB', 'analysis_area', '未分类', 'DT', 'excel_name', 'section'];

      // 遍历行数据中的字段
      for (const key in rowData) {
        const value = rowData[key];

        const shouldExclude =
          excludeFields.includes(key) ||
          value === 0 ||
          typeof value !== 'number' ||
          key.toLowerCase().includes('id');

        if (!shouldExclude) {
          typesAndValues.push({
            name: key,
            value: value
          });
        }
      }

      // 获取所有夹杂物类型名称作为X轴数据
      const xAxisData = typesAndValues.map(item => item.name);

      // 预定义一组鲜艳的颜色
      const colors = [
        '#5DA5DA', '#60BD68', '#F15854', '#B276B2', '#DECF3F',
        '#F17CB0', '#B2912F', '#4D4D4D', '#66C2A5', '#FC8D62',
        '#8DA0CB', '#E78AC3', '#A6D854', '#FFD92F', '#E5C494',
        '#7EA7D8', '#94D0C0', '#D1A7C7', '#BBBF4A', '#9B9B9B'
      ];

      // 使用单个系列，但为每个数据项设置不同颜色
      const series = [{
        name: 'Inclusion Density',
        type: 'bar',
        barWidth: '60%',
        data: typesAndValues.map((item, index) => ({
          value: item.value,
          // 为每个数据项设置独特的颜色
          itemStyle: {
            color: colors[index % colors.length]
          }
        })),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontSize: 16,
          fontWeight: 'bold',
          fontFamily: 'Times New Roman',
          //textShadowColor: 'rgba(0, 0, 0, 0.2)',
          //textShadowBlur: 2
        }
      }];

      return {
        xAxisData: xAxisData,
        series: series,
        legendData: ['Inclusion Density']
      };
    },
    // <!-----------------------------------------图三初始化------------------------------------------------------------------------------>
    initEcharts3(chartData) {
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
      }

      if (!this.$refs.chart2) {
        console.error('Chart DOM element not found');
        return;
      }

      const pixelRatio = window.devicePixelRatio || 1;
      const chart = echarts.init(this.$refs.chart2, null, {
        devicePixelRatio: 2.5, // 添加这个来提高清晰度
        renderer: 'canvas'
      });

      // 计算数据中的最大值，并设置为Y轴最大值的1.2倍
      let maxValue = 0;

      // 检查所有series的数据
      if (chartData.series && Array.isArray(chartData.series)) {
        chartData.series.forEach(series => {
          if (series.data && Array.isArray(series.data)) {
            series.data.forEach(item => {
              // 处理多种数据格式
              let value;
              if (typeof item === 'number') {
                value = item;
              } else if (typeof item === 'object' && item !== null) {
                value = item.value || item.y || 0;
              } else {
                value = parseFloat(item) || 0;
              }
              
              if (value > maxValue) {
                maxValue = value;
              }
            });
          }
        });
      }

      // 确保最大值计算正确
      const yAxisMax = maxValue > 0 ? Math.ceil(maxValue * 1.2) : 5.0;

      console.log('计算的maxValue:', maxValue);
      console.log('设置的yAxisMax:', yAxisMax);

      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show: false  // 隐藏图例，因为我们已经通过颜色区分了不同类型
        },
        grid: {
          top: '12%',  // 往下再移动20px左右
          left: '20%',  // 往左再移动15px左右
          right: '25%',
          bottom: '12%',  // 为x轴标签留出空间
          containLabel: true,
          // 添加边框
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },
        xAxis: {
          type: 'category',
          data: chartData.xAxisData,
          axisTick: {
            show: false  // 不显示x轴刻度线
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          axisLabel: {
            interval: 0,
            rotate: -45,
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman',
            fontWeight: 'bold',
            align: 'left',
            verticalAlign: 'top',
            padding: [0, 0, 0, 0],
            margin: 10,
            color: '#000000'
          },
          name: '夹杂物种类', // 添加X轴标题
          nameLocation: 'middle',
          nameGap: 80,
          nameTextStyle: {
            padding: [5, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        },
        yAxis: {
          name: '夹杂物数密度 /mm²',
          nameLocation: 'middle',
          type: 'value',
          nameRotate: 90,
          nameGap: 50,
          max: yAxisMax,  // 动态计算的最大值（数据最大值的1.2倍）
          axisTick: {
            show: true,
            inside: true  // y轴刻度线向内
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          splitLine: {
            show: true  // 不显示横线
          },
          nameTextStyle: {
            align: 'center',
            padding: [0, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman',
          },
          axisLabel: {
            fontSize: 16,
            fontWeight: 'bold',  
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          }
        },
        series: chartData.series
      };

      chart.setOption(option);  //显示图表
      this.chart = chart;       //可以更新已存在图表

      const resizeHandler = () => {
        chart.resize();
      };
      window.addEventListener('resize', resizeHandler);

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart) {
          this.chart.dispose();
          this.chart = null;
        }
      });

      setTimeout(() => {
        this.ht3Url = chart.getDataURL({
          type: 'png',
          pixelRatio: 3,
          backgroundColor: '#fff'
        });
      }, 1000);
    },


    // <!-----------------------------------------图四表点击事件-------------------------------------------------------------------------->
    handleSelectionChange6(val) {
      // 确保 val 是数组
      if (!Array.isArray(val)) {
        console.warn("Expected an array but got an object. Wrapping it in an array.");
        val = [val]; // 将对象包装成数组
      }

      // 清空所有行的 index
      this.htTableData6.forEach((el) => {
        this.$set(el, 'index', "");
      });

      // 更新选中的行数据列表
      this.selectIdList = val;

      // 为选中的行生成序号
      this.selectIdList.forEach((i, idx) => {
        this.htTableData6.forEach((el) => {
          if (i.SNUMB == el.SNUMB) {
            this.$set(el, 'index', idx + 1);  // 设置当前行的 index
          }
        });
      });

      // 初始化统计图6
      this.initEcharts6(this.selectIdList);
    },
    // <!-----------------------------------------图四初始化------------------------------------------------------------------------------>
    initEcharts6(values) {
  // 如果没有数据，清空并销毁图表
  if (!values || values.length === 0) {
    if (this.chart6) {
      this.chart6.clear();
      this.chart6.dispose();
      this.chart6 = null;
    }
    return;
  }

  // 如果已经存在图表，先销毁
  if (this.chart6) {
    this.chart6.dispose();
    this.chart6 = null;
  }

  // 创建颜色调色板
  const colorPalette = [
    '#000000',   // 黑色
    '#FF0000',   // 红色
    '#0000FF',   // 蓝色
    '#008000',   // 绿色
    '#FFA500',   // 橙色
    '#800080',   // 紫色
    '#00FFFF',   // 青色
    '#FF00FF',   // 品红
    '#008080',   // 深青
    '#800000',   // 栗色
    '#FFD700',   // 金色
    '#4B0082',   // 靛蓝
    '#20B2AA',   // 浅海洋绿
    '#8B4513',   // 马鞍棕
    '#2E8B57'    // 海洋绿
  ];

  // 创建新的图表实例
  this.chart6 = echarts.init(this.$refs.chart6);

  // 遍历所有样品名称
  var names = values.map(i => i.section);

  // 提取所有元素含量数据
  var elements = ['N', 'O', 'F', 'S', 'Ce', 'Ca', 'Mg', 'Al', 'Ti', 'Si', 'Mn'];
  var elementData = {};

  // 初始化每个元素的数据数组
  elements.forEach(element => {
    elementData[element] = [];
  });

  // 填充数据
  values.forEach((item) => {
    elements.forEach(element => {
      const value = item[`${element}_wt_percent`];
      elementData[element].push(value !== undefined && value !== null ? value : 0);
    });
  });

  // 🔴 智能计算Y轴最大值和刻度间隔（增加顶部空间）
  let maxValue = 0;

  // 遍历所有元素的所有数据，找到最大值
  elements.forEach(element => {
    elementData[element].forEach(value => {
      const numValue = parseFloat(value) || 0;
      if (numValue > maxValue) {
        maxValue = numValue;
      }
    });
  });

  // 🔴 根据数据范围智能计算Y轴最大值和刻度间隔（保留20%顶部空间）
  let yAxisMax, interval;
  
  if (maxValue <= 10) {
    // 最大值<=10：向上取整到5的倍数，并增加20%空间
    yAxisMax = Math.ceil(maxValue * 1.2 / 5) * 5;
    if (yAxisMax < 5) yAxisMax = 5;
    interval = yAxisMax / 5;
  } else if (maxValue <= 50) {
    // 最大值<=50：向上取整到10的倍数，并增加20%空间
    yAxisMax = Math.ceil(maxValue * 1.2 / 10) * 10;
    interval = yAxisMax / 5;
  } else {
    // 最大值>50：向上取整到20的倍数，并增加20%空间
    yAxisMax = Math.ceil(maxValue * 1.2 / 20) * 20;
    interval = yAxisMax / 5;
  }

  console.log('元素含量最大值:', maxValue);
  console.log('计算中间值(maxValue * 1.2):', maxValue * 1.2);
  console.log('Y轴设置最大值:', yAxisMax);
  console.log('Y轴刻度间隔:', interval);

  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: names,
      type: 'scroll',
      orient: 'vertical',
      right: '5%',
      top: '10%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      },
      backgroundColor: 'rgba(255,255,255,0.85)',
      borderColor: 'rgba(200,200,200,0.5)',
      borderWidth: 1,
      borderRadius: 4,
      padding: [10, 12, 10, 12]
    },
    grid: {
      left: '20%',
      right: '25%',
      bottom: '12%',
      top: '12%',
      containLabel: true,
      borderWidth: 2,
      borderColor: '#000000',
      show: true
    },
    xAxis: [{
      type: 'category',
      data: elements,
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000'
        }
      },
      axisLabel: {
        fontSize: 16,
        fontWeight: 'bold',
        fontFamily: 'Times New Roman',
        rotate: 30,
        margin: 10,
        color: '#2e2d2d',
        padding: [5, 0, 5, 0],
        formatter: function (value) {
          return value.length > 5 ? value.substring(0, 5) + '...' : value;
        }
      },
      name: '夹杂物中元素',
      nameLocation: 'middle',
      nameGap: 50,
      nameTextStyle: {
        padding: [5, 0, 0, 0],
        color: '#2e2d2d',
        fontSize: 24,
        fontWeight: 'bold',
        fontFamily: 'Times New Roman'
      },
      splitLine: {
        show: true,
        alignWithLabel: true,
        interval: 0,
        lineStyle: {
          type: 'dashed',
          color: '#eee',
          width: 1
        }
      },
      boundaryGap: true,
      z: 10
    }],
    yAxis: [{
      type: 'value',
      name: '元素含量/%',
      nameLocation: 'middle',
      nameRotate: 90,
      nameGap: 50,
      
      // 🔴 优化后的Y轴配置
      min: 0,
      max: yAxisMax,
      interval: interval,
      
      axisTick: {
        show: true,
        inside: true
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#000'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#e5e5e5',
          width: 1
        }
      },
      nameTextStyle: {
        align: 'center',
        padding: [0, 0, 0, 0],
        color: '#2e2d2d',
        fontSize: 24,
        fontWeight: 'bold',
        fontFamily: 'Times New Roman',
      },
      axisLabel: {
        fontSize: 16, 
        fontWeight: 'bold',
        color: '#2e2d2d',
        fontFamily: 'Times New Roman',
        formatter: function (value) {
          // 整数直接显示，小数保留1位
          return value % 1 === 0 ? value : value.toFixed(1);
        }
      }
    }],
    series: names.map((name, idx) => ({
      name: name,
      type: 'line',
      symbol: 'diamond',
      symbolSize: 10,
      itemStyle: {
        color: colorPalette[idx % colorPalette.length]
      },
      lineStyle: {
        color: colorPalette[idx % colorPalette.length],
        width: 2,
      },
      emphasis: {
        focus: 'series',
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      },
      data: elements.map(element =>
        elementData[element][idx] || 0
      )
    }))
  };

  this.chart6.setOption(option);

  // 添加resize监听
  const resizeHandler = () => {
    if (this.chart6 && !this.chart6.isDisposed()) {
      this.chart6.resize();
    }
  };
  window.addEventListener('resize', resizeHandler);

  // 组件销毁时移除监听
  this.$once('hook:beforeDestroy', () => {
    window.removeEventListener('resize', resizeHandler);
    if (this.chart6) {
      this.chart6.dispose();
      this.chart6 = null;
    }
  });

  // 使用 setTimeout 确保图表已经完全渲染
  setTimeout(() => {
    if (this.chart6 && !this.chart6.isDisposed()) {
      this.ht6Url = this.chart6.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff',
      });
    }
  }, 1000);
},

    // <!-----------------------------------------图五表点击事件-------------------------------------------------------------------------->
    handleSelectionChange7(val) {
      // 确保 val 是数组
      if (!Array.isArray(val)) {
        console.warn("Expected an array but got an object. Wrapping it in an array.");
        val = [val]; // 将对象包装成数组
      }

      // 清空所有行的 index
      this.htTableData7.forEach((el) => {
        this.$set(el, 'index', "");
      });

      // 更新选中的行数据列表
      this.selectIdList = val;

      // 为选中的行生成序号
      this.selectIdList.forEach((i, idx) => {
        this.htTableData7.forEach((el) => {
          if (i.SNUMB == el.SNUMB) {
            this.$set(el, 'index', idx + 1);  // 设置当前行的 index
          }
        });
      });

      // 初始化统计图7
      this.initEcharts7(this.selectIdList);
    },
    
    // <!-----------------------------------------图五行点击事件（循环切换图表类型）-------------------------------------------------------------------------->
    async handleRowClick7(row, column, event) {
      // 检查是否勾选了数据
      if (this.selectIdList.length === 0) {
        this.$message.warning('请先勾选要显示的数据行');
        return;
      }
      
      // 检查原始数据是否存在
      if (!this.jzwTableData2 || this.jzwTableData2.length === 0) {
        this.$message.error('没有原始夹杂物数据！请先点击"夹杂物自定义筛选"按钮加载数据。');
        return;
      }
      
      // 筛选选中样品的原始数据
      const selectedSections = this.selectIdList.map(item => ({
        excel_name: item.excel_name || item.Excel_name,
        section: item.section || item.Section
      }));
      
      const rawData = this.jzwTableData2.filter(item => {
        return selectedSections.some(selected => {
          const rawExcel = item.excel_name || item.Excel_name;
          const rawSection = item.section || item.Section;
          const excelMatch = (rawExcel || '').trim() === (selected.excel_name || '').trim();
          const sectionMatch = (rawSection || '').trim() === (selected.section || '').trim();
          return excelMatch && sectionMatch;
        });
      });
      
      if (rawData.length === 0) {
        this.$message.error('选中的样品没有对应的原始夹杂物数据！');
        return;
      }
      
      // 切换图表类型（循环 0-4）
      this.currentChartType = (this.currentChartType + 1) % 5;
      
      // 构建请求数据
      const postData = {
        data: this.selectIdList,
        raw_data: this.currentChartType > 0 ? rawData : [],
        chart_type: this.currentChartType,
        use_raw_data: this.currentChartType > 0
      };
      
      try {
        // 请求后端接口
        const response = await service.post('statistic7_chart', postData);
        
        // 检查响应数据
        if (!response || !response.data || response.data.length === 0) {
          this.$message.error('没有获取到图表数据');
          return;
        }
        
        // 显示当前方案名称
        const schemeNames = [
          '原始方案 (0-2, 2-5, 5-10, ≥10μm)',
          '方案1 (0.5-1, 1-3, 3-5, 5-10, ≥10μm)',
          '方案2 (1-3, 3-5, 5-10, ≥10μm)',
          '方案3 (2-4, 4-5, 5-10, ≥10μm)',
          '方案4 (5-7, 7-10, ≥10μm)'
        ];
        this.$message.success('切换到：' + schemeNames[this.currentChartType]);
        
        // 渲染图表
        this.initEcharts7WithBackendData(response);
        
      } catch (error) {
        console.error('获取图表数据失败:', error);
        const errorMsg = error.response?.data?.message || error.response?.data?.error || error.message || '未知错误';
        this.$message.error('获取图表数据失败: ' + errorMsg);
      }
    },


    // <!-----------------------------------------图五初始化----------------------------------------------------------------------------->
    initEcharts7(values) {
      // 如果没有数据，清空并销毁图表
      // 修改为：
      if (!values || values.length === 0) {  // 改为 values 而不是 selectedRows
        if (this.chart7) {
          this.chart7.clear();
          this.chart7.dispose();
          this.chart7 = null;
        }
        return;
      }

      // 如果已经存在图表，先销毁
      if (this.chart7) {
        this.chart7.dispose();
        this.chart7 = null;
      }

      // 创建新的图表实例
      this.chart7 = echarts.init(this.$refs.chart7);

      // 定义尺寸区间
      var sizeCategories = ['0-2μm', '2-5μm', '5-10μm', '>10μm'];
      var seriesData = {}; // 用于存储不同 section 的数据

      // 定义颜色调色板
      const colorPalette = [
        '#000000', // 黑色
        '#FF0000', // 红色
        '#0000FF', // 蓝色
        '#008000', // 绿色
        '#FFA500', // 橙色
        '#800080', // 紫色
        '#00FFFF', // 青色
        '#FF00FF', // 品红
        '#008080', // 深青
        '#800000'  // 栗色
      ];

      // 初始化 seriesData
      values.forEach((item) => {
        const section = item.section;
        if (!seriesData[section]) {
          seriesData[section] = {
            name: section,
            data: [0, 0, 0, 0] // 初始化四个尺寸区间的数量
          };
        }

        // 根据后端返回的单位面积夹杂物数量更新对应的尺寸区间数量
        seriesData[section].data[0] += item['inclusions_size_0-2μm'] || 0; // 0-2μm
        seriesData[section].data[1] += item['inclusions_size_2-5μm'] || 0; // 2-5μm
        seriesData[section].data[2] += item['inclusions_size_5-10μm'] || 0; // 5-10μm
        seriesData[section].data[3] += item['inclusions_size_10+μm'] || 0; // >10μm
      });

      // **新增：动态计算Y轴最大值**
      let maxValue = 0;

      // 遍历所有section的所有数据，找到最大值
      Object.values(seriesData).forEach(sectionData => {
        sectionData.data.forEach(value => {
          const numValue = parseFloat(value) || 0;
          if (numValue > maxValue) {
            maxValue = numValue;
          }
        });
      });

// 计算Y轴最大值（数据最大值的1.2倍，至少为1）
const yAxisMax = Math.max(Math.ceil(maxValue * 1.2), 1);

console.log('夹杂物数密度最大值:', maxValue);
console.log('Y轴设置最大值:', yAxisMax);

      // 计算柱子宽度
      const seriesCount = Object.keys(seriesData).length;
      const barWidth = seriesCount > 0 ? `${Math.max(30 / seriesCount, 10)}%` : '30%';

      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        title: {
          text: '夹杂物尺寸分布-原始方案 (0-2, 2-5, 5-10, ≥10μm)',
          left: 'center',
          top: '8%',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            color: '#333'
          }
        },

        legend: {
          data: Object.keys(seriesData), // 使用 section 作为图例
          orient: 'vertical',
          right: '5%',
          top: '10%',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333',
            fontFamily: 'Times New Roman'
          },
          backgroundColor: 'rgba(255,255,255,0.85)',
          borderColor: 'rgba(200,200,200,0.5)',
          borderWidth: 1,
          borderRadius: 4,
          padding: [10, 12, 10, 12]
        },
        grid: {
          left: '20%',  // 向右移动，避免左侧标题被遮盖
          right: '25%',  // 为右侧图例留出空间
          bottom: '12%',  // 为x轴标题留出空间
          top: '15%',
          containLabel: true,
          width: 'auto',
          // 添加边框
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },
        xAxis: [{
          type: 'category',
          data: sizeCategories, // 使用尺寸区间作为 X 轴
          axisTick: {
            show: false  // 不显示x轴刻度线,            
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          axisLabel: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          },
          name: '夹杂物尺寸(μm)', // 添加X轴标题
          nameLocation: 'middle', // 标题位置
          nameGap: 50, // 标题与轴线的距离
          nameTextStyle: {
            padding: [5, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        }],
        yAxis: [{
          type: 'value',
          name: '夹杂物数密度(个/mm²)',
          nameLocation: 'middle',
          nameRotate: 90,
          nameGap: 50,
          max: yAxisMax, // **新增：设置动态计算的最大值**
          axisTick: {
            show: true,
            inside: true  // y轴刻度线向内
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          splitLine: {
            show: true  // 显示横线
          },
          nameTextStyle: {
            align: 'center',
            padding: [0, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman',
          },
          position: 'left',
          axisLabel: {
            formatter: '{value}',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          }
        }],
        series: Object.values(seriesData).map((sectionData, index) => ({
          name: sectionData.name,
          type: 'bar',
          data: sectionData.data,
          itemStyle: {
            // 使用颜色调色板，确保每个系列颜色不同
            color: colorPalette[index % colorPalette.length]
          },
          barWidth: barWidth, // 动态计算柱子宽度
          barGap: '10%', // 柱子间隔
        }))
      };

      this.chart7.setOption(option);

      // 添加resize监听
      const resizeHandler = () => {
        this.chart7.resize();
      };
      window.addEventListener('resize', resizeHandler);

      // 组件销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
      });

      // 使用 setTimeout 确保图表已经完全渲染
      setTimeout(() => {
        this.ht7Url = this.chart7.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff',
        });
      }, 1000);
    },    

    // <!-----------------------------------------图五初始化（支持多种分类方案）----------------------------------------------------------------------------->
  initEcharts7WithBackendData(backendResponse) {
    // 解构数据
    const { data, scheme_name, ranges, chart_type } = backendResponse;
    
    // 数据验证
    if (!data || !Array.isArray(data) || data.length === 0) {
      if (this.chart7) {
        this.chart7.clear();
      }
      this.$message.warning('没有可显示的数据');
      return;
    }

    if (!ranges || !Array.isArray(ranges) || ranges.length === 0) {
      this.$message.error('图表数据格式错误：缺少ranges信息');
      return;
    }

    // 销毁旧图表
    if (this.chart7) {
      this.chart7.dispose();
      this.chart7 = null;
    }

    // 使用 $nextTick 确保DOM更新
    this.$nextTick(() => {
      this.chart7 = echarts.init(this.$refs.chart7);

      // 定义颜色调色板
      const colorPalette = [
        '#000000', '#FF0000', '#0000FF', '#008000', '#FFA500',
        '#800080', '#00FFFF', '#FF00FF', '#008080', '#800000'
      ];

      // 构建系列数据
      const seriesData = {};
      
      data.forEach(item => {
        const section = item.section;
        if (!section) return;
        
        if (!seriesData[section]) {
          seriesData[section] = {
            name: section,
            data: []
          };
        }
        
        // 提取密度数据
        if (item.ranges && Array.isArray(item.ranges)) {
          seriesData[section].data = item.ranges.map(range => {
            return parseFloat(range.density) || 0;
          });
        } else {
          seriesData[section].data = new Array(ranges.length).fill(0);
        }
      });

      // 验证系列数据
      if (Object.keys(seriesData).length === 0) {
        this.$message.error('图表数据处理失败');
        return;
      }

      // 计算柱子宽度
      const seriesCount = Object.keys(seriesData).length;
      const barWidth = seriesCount > 0 ? `${Math.max(30 / seriesCount, 10)}%` : '30%';

      // 计算Y轴最大值
      let maxValue = 0;
      Object.values(seriesData).forEach(sectionData => {
        sectionData.data.forEach(value => {
          if (value > maxValue) {
            maxValue = value;
          }
        });
      });
      const yAxisMax = Math.max(Math.ceil(maxValue * 1.2), 1);

      // 图表配置
      const option = {
        title: {
          text: `夹杂物尺寸分布 - ${scheme_name}`,
          left: 'center',
          top: '8%',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: Object.keys(seriesData),
          orient: 'vertical',
          right: '5%',
          top: '10%',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333',
            fontFamily: 'Times New Roman'
          },
          backgroundColor: 'rgba(255,255,255,0.85)',
          borderColor: 'rgba(200,200,200,0.5)',
          borderWidth: 1,
          borderRadius: 4,
          padding: [10, 12, 10, 12]
        },
        grid: {
          left: '20%',
          right: '25%',
          bottom: '12%',
          top: '15%',
          containLabel: true,
          width: 'auto',
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },
        xAxis: [{
          type: 'category',
          data: ranges,
          axisTick: {
            show: false,  // 不显示x轴刻度线        
            inside: true
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          axisLabel: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          },
          name: '夹杂物尺寸(μm)',
          nameLocation: 'middle',
          nameGap: 50,
          nameTextStyle: {
            padding: [5, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        }],
        yAxis: [{
          type: 'value',
          name: '夹杂物数密度(个/mm²)',
          nameLocation: 'middle',
          nameRotate: 90,
          nameGap: 50,
          max: yAxisMax,
          axisTick: {
            show: true,
            inside: true
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          splitLine: {
            show: true
          },
          nameTextStyle: {
            align: 'center',
            padding: [0, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman',
          },
          position: 'left',
          axisLabel: {
            formatter: '{value}',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          }
        }],
        series: Object.values(seriesData).map((sectionData, index) => ({
          name: sectionData.name,
          type: 'bar',
          data: sectionData.data,
          itemStyle: {
            color: colorPalette[index % colorPalette.length]
          },
          barWidth: barWidth,
          barGap: '10%',
        }))
      };
      
      this.chart7.setOption(option);

      // 添加resize监听
      const resizeHandler = () => {
        if (this.chart7) {
          this.chart7.resize();
        }
      };
      window.addEventListener('resize', resizeHandler);

      // 组件销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart7) {
          this.chart7.dispose();
          this.chart7 = null;
        }
      });

      // 生成截图
      setTimeout(() => {
        if (this.chart7) {
          this.ht7Url = this.chart7.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff',
          });
        }
      }, 500);
    });
  },

    // <!-----------------------------------------图六：双Y轴点线图相关方法-------------------------------------------------------------------------->
    handleSelectionChange8(val) {
      // 确保 val 是数组
      if (!Array.isArray(val)) {
        val = [val];
      }
      
      // 清空 index
      this.htTableData8.forEach((el) => {
        this.$set(el, 'index', "");
      });
      
      this.selectIdList = val;
      
      // 为选中的行添加 index
      this.selectIdList.forEach((i, idx) => {
        this.htTableData8.forEach((el) => {
          if (i.SNUMB == el.SNUMB) {
            this.$set(el, 'index', idx + 1);
          }
        });
      });
      
      // 如果没有 min/max，调用接口查询
      if (val.length > 0 && val[0].min_diameter === undefined) {
        service.post('statistic8', val).then(res => {
          if (res.data && res.data.length > 0) {
            // 更新表格数据中的 min/max
            res.data.forEach((item) => {
              this.htTableData8.forEach((el) => {
                if (el.excel_name === item.excel_name && el.section === item.section) {
                  this.$set(el, 'min_diameter', item.min_diameter);
                  this.$set(el, 'max_diameter', item.max_diameter);
                }
              });
            });
            this.initEcharts8(res.data);
          }
        }).catch(err => {
          console.error('查询失败:', err);
          this.$message.error('查询失败');
        });
      } else {
        this.initEcharts8(val);
      }
    },

    htTableClick8(row, column, event) {
      // 🔴 修复：传递数组
      service.post('statistic8', [row]).then(res => {
        // 🔴 修复：使用后端返回的数据
        if (res.data && res.data.length > 0) {
          this.initEcharts8(res.data);
        } else {
          this.$message.warning('没有查询到该样品的数据');
        }
      }).catch(err => {
        console.error('查询图表6数据失败:', err);
        this.$message.error('查询失败');
      });
    },

    initEcharts8(values) {
      // 空数据处理
      if (!values || values.length === 0) {
        if (this.chart8) {
          this.chart8.clear();
          this.chart8.dispose();
          this.chart8 = null;
        }
        return;
      }

      // 数据准备
      const sampleNames = values.map(item => 
        item.section || item.Section || item.SNUMB || item.snumb || '未知样品'
      );
      
      const minDiameters = values.map(item => {
        const val = parseFloat(item.min_diameter);
        return isNaN(val) ? null : val;
      });
      
      const maxDiameters = values.map(item => {
        const val = parseFloat(item.max_diameter);
        return isNaN(val) ? null : val;
      });

      // 动态计算Y轴最大值
      let maxMinValue = 0;
      minDiameters.forEach(item => {
        const value = parseFloat(item) || 0;
        if (value > maxMinValue) {
          maxMinValue = value;
        }
      });
      const leftYAxisMax = Math.max(Math.ceil(maxMinValue * 1.2), 1);

      let maxMaxValue = 0;
      maxDiameters.forEach(item => {
        const value = parseFloat(item) || 0;
        if (value > maxMaxValue) {
          maxMaxValue = value;
        }
      });
      const rightYAxisMax = Math.max(Math.ceil(maxMaxValue * 1.2), 1);

      // 销毁已存在的图表
      if (this.chart8) {
        this.chart8.dispose();
        this.chart8 = null;
      }

      const chartDom = this.$refs.chart8;
      if (!chartDom) {
        console.error('Chart8 DOM element not found');
        return;
      }

      const chart = echarts.init(chartDom);
      this.chart8 = chart;

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: (params) => {
            let result = `${params[0].name}<br/>`;
            params.forEach(item => {
              const value = item.value !== null ? item.value.toFixed(2) : '无数据';
              result += `${item.marker} ${item.seriesName}: ${value} μm<br/>`;
            });
            return result;
          }
        },    
        
        legend: {
          orient: 'vertical',
          right: '5%',
          top: '10%',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333'
          },
          backgroundColor: 'rgba(255,255,255,0.85)',
          borderColor: 'rgba(200,200,200,0.5)',
          borderWidth: 1,
          borderRadius: 4,
          padding: [10, 12, 10, 12],
          data: ['ECD最小值', 'ECD最大值']
        },
        grid: {
          top: '12%',
          left: '20%',
          right: '25%',
          bottom: '15%',
          borderWidth: 2,
          borderColor: '#000000',
          show: true
        },    
        xAxis: {
          type: 'category',
          data: sampleNames,
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000'
            }
          },
          splitLine: {
            show: true,
            alignWithLabel: true
          },      
          axisLabel: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman',
            rotate: sampleNames.length > 10 ? 45 : 0
          },
          name: '样品名称',
          nameLocation: 'middle',
          nameGap: 50,
          nameTextStyle: {
            padding: [5, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        },
        yAxis: [
          {
            type: 'value',
            name: 'ECD最小值(μm)',
            nameLocation: 'middle',
            nameRotate: 90,
            nameGap: 50,
            max: leftYAxisMax,
            axisTick: {
              show: true,
              inside: true
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: true
            },
            nameTextStyle: {
              align: 'center',
              padding: [0, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,
              fontWeight: 'bold',
              fontFamily: 'Times New Roman'
            },
            position: 'left',
            axisLabel: {
              formatter: '{value}',
              fontSize: 16,
              fontWeight: 'bold',
              color: '#2e2d2d',
              fontFamily: 'Times New Roman'
            }
          },
          {
            type: 'value',
            name: 'ECD最大值(μm)',
            nameLocation: 'middle',
            nameRotate: 90,
            nameGap: 50,
            max: rightYAxisMax,
            axisTick: {
              show: true,
              inside: true
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: false
            },
            nameTextStyle: {
              align: 'center',
              padding: [0, 0, 0, 0],
              color: '#2e2d2d',
              fontSize: 24,
              fontWeight: 'bold',
              fontFamily: 'Times New Roman'
            },
            position: 'right',
            axisLabel: {
              formatter: '{value}',
              fontSize: 16,
              fontWeight: 'bold',
              color: '#2e2d2d',
              fontFamily: 'Times New Roman'
            }
          }
        ],
        series: [
          {
            name: 'ECD最小值',
            type: 'line',
            yAxisIndex: 0,
            data: minDiameters,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: '#5470c6',
              width: 3
            },
            itemStyle: {
              color: '#5470c6'
            },
            connectNulls: false
          },
          {
            name: 'ECD最大值',
            type: 'line',
            yAxisIndex: 1,
            data: maxDiameters,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: '#91cc75',
              width: 3
            },
            itemStyle: {
              color: '#91cc75'
            },
            connectNulls: false
          }
        ]
      };

      chart.setOption(option);

      // 添加resize监听
      const resizeHandler = () => {
        if (chart) {
          chart.resize();
        }
      };
      window.addEventListener('resize', resizeHandler);

      // 组件销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart8) {
          this.chart8.dispose();
          this.chart8 = null;
        }
      });

      // 生成截图
      setTimeout(() => {
        if (this.chart8) {
          this.ht8Url = this.chart8.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff'
          });
        }
      }, 1000);
    },

    // <!-----------------------------------------图七：三元相图相关方法-------------------------------------------------------------------------->
    // ========== 选择表格行（多选） ==========
    handleSelectionChange9(val) {
      console.log('选中的样品:', val);
      
      // 先清空所有行的选择顺序
      this.htTableData9.forEach(row => {
        this.$set(row, 'selectionOrder', '');
      });
      
      // 为选中的行设置顺序
      val.forEach((selectedRow, index) => {
        const foundRow = this.htTableData9.find(row => 
          row.SNUMB === selectedRow.SNUMB && row.section === selectedRow.section
        );
        if (foundRow) {
          this.$set(foundRow, 'selectionOrder', index + 1);
        }
      });
      
      // 保存选中的样品
      this.selectedSamples = val;
      
      if (val.length === 0) {
        // 清空图表
        if (this.chart9) {
          this.chart9.clear();
        }
        if (this.chart10) {
          this.chart10.clear();
        }
        return;
      }
      
      // 提取图1和图2的数据
      const chart1Data = this.extractChartData(val, 1);
      const chart2Data = this.extractChartData(val, 2);
      
      console.log(`图1数据点: ${chart1Data.length} 个`);
      console.log(`图2数据点: ${chart2Data.length} 个`);
      
      // 绘制两个图表
      this.initTernaryChart1(chart1Data);
      this.initTernaryChart2(chart2Data);
    },

    // =========================================== 提取图表数据 ============================
    extractChartData(samples, chartNum) {
      /**
       * 从选中的样品中提取指定图表的数据
       * @param {Array} samples - 选中的样品数组
       * @param {Number} chartNum - 图表编号（1 或 2）
       * @returns {Array} 数据点数组
       */
      const allPoints = [];
      
      samples.forEach(sample => {
        const section = sample.section;
        const count = sample[`chart${chartNum}_count`];
        
        // 遍历该样品的所有数据点
        for (let i = 1; i <= count; i++) {
          const key = `${chartNum}-${i}`;
          const point = sample[key];
          
          if (point && point.x !== undefined && point.y !== undefined && point.z !== undefined) {
            allPoints.push({
              section: section,
              SNUMB: point.SNUMB,
              x: point.x,
              y: point.y,
              z: point.z
            });
          }
        }
      });
      
      return allPoints;
    },

    // ===================================== 图1：Al2O3-MgO-CaO 三元相图 ==========
    initTernaryChart1(values) {
      if (!values || values.length === 0) {
        if (this.chart9) {
          this.chart9.clear();
        }
        this.$message.info('图1：请先在左侧表格中选择样品');
        return;
      }

      if (this.chart9) {
        this.chart9.dispose();
        this.chart9 = null;
      }

      const chartDom = this.$refs.chart9;
      if (!chartDom) {
        console.error('Chart9 DOM element not found');
        return;
      }

      const chart = echarts.init(chartDom);
      this.chart9 = chart;

      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
        '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#d4ec59'
      ];

      const groupedData = {};
      
      values.forEach((item, index) => {
        const al2o3 = parseFloat(item.x) || 0;
        const mgo = parseFloat(item.y) || 0;
        const cao = parseFloat(item.z) || 0;
        
        const x_coord = (al2o3 + 0.5 * mgo) / 100;
        const y_coord = (Math.sqrt(3) / 2 * mgo) / 100;
        
        const sampleName = item.section || '未知样品';
        
        if (!groupedData[sampleName]) {
          groupedData[sampleName] = [];
        }
        
        groupedData[sampleName].push({
          name: `${item.SNUMB}`,
          value: [x_coord, y_coord],
          originalData: {
            SNUMB: item.SNUMB,
            section: item.section,
            al2o3: al2o3,
            mgo: mgo,
            cao: cao
          }
        });
      });

      const triangleBorder = {
        type: 'line',
        coordinateSystem: 'cartesian2d',
        data: [
          [0, 0],
          [1, 0],
          [0.5, Math.sqrt(3) / 2],
          [0, 0]
        ],
        lineStyle: { 
          color: '#000', 
          width: 2 
        },
        symbol: 'none',
        z: 1
      };

      const gridLines = [];
      for (let i = 1; i < 10; i++) {
        const t = i * 0.1;
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [t / 2, t * Math.sqrt(3) / 2],
            [1 - t / 2, t * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [t, 0],
            [0.5 + t / 2, (1 - t) * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [1 - t, 0],
            [0.5 - t / 2, (1 - t) * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
      }

      const scatterSeries = [];
      let colorIndex = 0;
      
      Object.keys(groupedData).forEach(sampleName => {
        scatterSeries.push({
          name: sampleName,
          type: 'scatter',
          coordinateSystem: 'cartesian2d',
          data: groupedData[sampleName],
          symbolSize: 8,
          itemStyle: {
            color: colors[colorIndex % colors.length],
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            scale: true,
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          z: 2
        });
        colorIndex++;
      });

      const markPointData = [];
      
      // 🔴 底边标签（CaO轴）- 排除0和100
      for (let i = 1; i < 10; i++) {  // 从1到9，排除0和10
        const t = i * 0.1;
        markPointData.push({
          coord: [t, -0.025],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'bottom',
            distance: 5,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }
      
      // 🔴 右边标签（Al₂O₃轴）- 排除0和100
      for (let i = 1; i < 10; i++) {  // 从1到9，排除0和10
        const t = i * 0.1;
        const x = 1 - t / 2;
        const y = t * Math.sqrt(3) / 2;
        
        markPointData.push({
          coord: [x, y],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'right',
            distance: 8,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }
      
      // 🔴 左边标签（MgO轴）- 排除0和100
      for (let i = 1; i < 10; i++) {  // 从1到9，排除0和10
        const t = i * 0.1;
        const x = t / 2;
        const y = t * Math.sqrt(3) / 2;
        
        markPointData.push({
          coord: [x, y],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'left',
            distance: 8,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }

      // 🔴 添加三个顶点的氧化物标签（无红点）
      markPointData.push(
        // CaO 顶点（左下角）
        {
          coord: [0, 0],
          value: '',
          label: {
            show: true,
            position: 'left',
            distance: 10,
            formatter: 'CaO',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,  // 🔴 改为极小
          itemStyle: {
            color: 'transparent'  // 🔴 透明
          }
        },
        // Al₂O₃ 顶点（右下角）
        {
          coord: [1, 0],
          value: '',
          label: {
            show: true,
            position: 'right',
            distance: 10,
            formatter: 'Al₂O₃',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,  // 🔴 改为极小
          itemStyle: {
            color: 'transparent'  // 🔴 透明
          }
        },
        // MgO 顶点（顶部）
        {
          coord: [0.5, Math.sqrt(3) / 2],
          value: '',
          label: {
            show: true,
            position: 'top',
            distance: 10,
            formatter: 'MgO',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,  // 🔴 改为极小
          itemStyle: {
            color: 'transparent'  // 🔴 透明
          }
        }
      );

      const labelSeries = {
        type: 'line',
        coordinateSystem: 'cartesian2d',
        data: [],
        markPoint: {
          animation: false,
          data: markPointData
        },
        lineStyle: {
          opacity: 0
        },
        symbol: 'none',
        silent: true,
        z: 10
      };

      const option = {
        title: {
          text: `Al₂O₃-MgO-CaO 三元相图 (共 ${values.length} 个数据点)`,
          left: 'center',
          top: '3%',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        },
        
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: '5%',
          top: '15%',
          data: Object.keys(groupedData),
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
                  }
        },    
        
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.seriesType === 'scatter' && params.data.originalData) {
              const data = params.data.originalData;
              return `<div style="padding: 8px;">
                        <div><strong>样品:</strong> ${data.section}</div>
                        <div><strong>序号:</strong> ${data.SNUMB}</div>
                        <div style="margin-top: 5px; border-top: 1px solid #ddd; padding-top: 5px;">
                          <div><strong>Al₂O₃:</strong> ${data.al2o3.toFixed(2)}%</div>
                          <div><strong>MgO:</strong> ${data.mgo.toFixed(2)}%</div>
                          <div><strong>CaO:</strong> ${data.cao.toFixed(2)}%</div>
                        </div>
                      </div>`;
            }
            return '';
          }
        },
        grid: {
          top: '15%',
          left: '12%',
          right: '18%',
          bottom: '15%',
          containLabel: false
        },
        xAxis: {
          type: 'value',
          min: -0.1,
          max: 1.1,
          show: false
        },
        yAxis: {
          type: 'value',
          min: -0.1,
          max: Math.sqrt(3) / 2 + 0.1,
          show: false
        },
        series: [
          triangleBorder,
          ...gridLines,
          labelSeries,
          ...scatterSeries
        ]
      };

      chart.setOption(option);

      const resizeHandler = () => {
        if (chart && !chart.isDisposed()) {
          chart.resize();
        }
      };
      window.addEventListener('resize', resizeHandler);

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart9) {
          this.chart9.dispose();
          this.chart9 = null;
        }
      });

      setTimeout(() => {
        if (chart && !chart.isDisposed()) {
          this.ht9Url = chart.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff',
          });
        }
      }, 1000);
    },

    // ==================================== 图2：Al2O3-TiO2-CaO 三元相图 ==========
    initTernaryChart2(values) {
      if (!values || values.length === 0) {
        if (this.chart10) {
          this.chart10.clear();
        }
        this.$message.info('图2：请先在左侧表格中选择样品');
        return;
      }

      if (this.chart10) {
        this.chart10.dispose();
        this.chart10 = null;
      }

      const chartDom = this.$refs.chart10;
      if (!chartDom) {
        console.error('Chart10 DOM element not found');
        return;
      }

      const chart = echarts.init(chartDom);
      this.chart10 = chart;

      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
        '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#d4ec59'
      ];

      const groupedData = {};
      
      values.forEach((item, index) => {
        const al2o3 = parseFloat(item.x) || 0;
        const tio2 = parseFloat(item.y) || 0;
        const cao = parseFloat(item.z) || 0;
        
        const x_coord = (al2o3 + 0.5 * tio2) / 100;
        const y_coord = (Math.sqrt(3) / 2 * tio2) / 100;
        
        const sampleName = item.section || '未知样品';
        
        if (!groupedData[sampleName]) {
          groupedData[sampleName] = [];
        }
        
        groupedData[sampleName].push({
          name: `${item.SNUMB}`,
          value: [x_coord, y_coord],
          originalData: {
            SNUMB: item.SNUMB,
            section: item.section,
            al2o3: al2o3,
            tio2: tio2,
            cao: cao
          }
        });
      });

      const triangleBorder = {
        type: 'line',
        coordinateSystem: 'cartesian2d',
        data: [
          [0, 0],
          [1, 0],
          [0.5, Math.sqrt(3) / 2],
          [0, 0]
        ],
        lineStyle: { 
          color: '#000', 
          width: 2 
        },
        symbol: 'none',
        z: 1
      };

      const gridLines = [];
      for (let i = 1; i < 10; i++) {
        const t = i * 0.1;
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [t / 2, t * Math.sqrt(3) / 2],
            [1 - t / 2, t * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [t, 0],
            [0.5 + t / 2, (1 - t) * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
        
        gridLines.push({
          type: 'line',
          coordinateSystem: 'cartesian2d',
          data: [
            [1 - t, 0],
            [0.5 - t / 2, (1 - t) * Math.sqrt(3) / 2]
          ],
          lineStyle: { 
            color: '#ddd', 
            width: 1, 
            type: 'dashed' 
          },
          symbol: 'none',
          z: 1
        });
      }

      const scatterSeries = [];
      let colorIndex = 0;
      
      Object.keys(groupedData).forEach(sampleName => {
        scatterSeries.push({
          name: sampleName,
          type: 'scatter',
          coordinateSystem: 'cartesian2d',
          data: groupedData[sampleName],
          symbolSize: 8,
          itemStyle: {
            color: colors[colorIndex % colors.length],
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            scale: true,
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          },
          z: 2
        });
        colorIndex++;
      });

      // 🔴 去掉刻度线部分

      const markPointData = [];
      
      // 🔴 底边标签（CaO轴）- 排除0和100
      for (let i = 1; i < 10; i++) {
        const t = i * 0.1;
        markPointData.push({
          coord: [t, -0.025],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'bottom',
            distance: 5,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }
      
      // 🔴 右边标签（Al₂O₃轴）- 排除0和100
      for (let i = 1; i < 10; i++) {
        const t = i * 0.1;
        const x = 1 - t / 2;
        const y = t * Math.sqrt(3) / 2;
        
        markPointData.push({
          coord: [x, y],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'right',
            distance: 8,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }
      
      // 🔴 左边标签（TiO₂轴）- 排除0和100
      for (let i = 1; i < 10; i++) {
        const t = i * 0.1;
        const x = t / 2;
        const y = t * Math.sqrt(3) / 2;
        
        markPointData.push({
          coord: [x, y],
          value: `${i * 10}`,
          label: {
            show: true,
            position: 'left',
            distance: 8,
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        });
      }

      // 🔴 添加三个顶点的氧化物标签（无红点）
      markPointData.push(
        // CaO 顶点（左下角）
        {
          coord: [0, 0],
          value: '',
          label: {
            show: true,
            position: 'left',
            distance: 10,
            formatter: 'CaO',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        },
        // Al₂O₃ 顶点（右下角）
        {
          coord: [1, 0],
          value: '',
          label: {
            show: true,
            position: 'right',
            distance: 10,
            formatter: 'Al₂O₃',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        },
        // TiO₂ 顶点（顶部）
        {
          coord: [0.5, Math.sqrt(3) / 2],
          value: '',
          label: {
            show: true,
            position: 'top',
            distance: 10,
            formatter: 'TiO₂',
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          symbol: 'circle',
          symbolSize: 0.1,
          itemStyle: {
            color: 'transparent'
          }
        }
      );

      const labelSeries = {
        type: 'line',
        coordinateSystem: 'cartesian2d',
        data: [],
        markPoint: {
          animation: false,
          data: markPointData
        },
        lineStyle: {
          opacity: 0
        },
        symbol: 'none',
        silent: true,
        z: 10
      };

      const option = {
        title: {
          text: `Al₂O₃-TiO₂-CaO 三元相图 (共 ${values.length} 个数据点)`,
          left: 'center',
          top: '3%',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          }
        },
        
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: '5%',
          top: '15%',
          data: Object.keys(groupedData),
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          }
        },
        
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.seriesType === 'scatter' && params.data.originalData) {
              const data = params.data.originalData;
              return `<div style="padding: 8px;">
                        <div><strong>样品:</strong> ${data.section}</div>
                        <div><strong>序号:</strong> ${data.SNUMB}</div>
                        <div style="margin-top: 5px; border-top: 1px solid #ddd; padding-top: 5px;">
                          <div><strong>Al₂O₃:</strong> ${data.al2o3.toFixed(2)}%</div>
                          <div><strong>TiO₂:</strong> ${data.tio2.toFixed(2)}%</div>
                          <div><strong>CaO:</strong> ${data.cao.toFixed(2)}%</div>
                        </div>
                      </div>`;
            }
            return '';
          }
        },
        grid: {
          top: '15%',
          left: '12%',
          right: '18%',
          bottom: '15%',
          containLabel: false
        },
        xAxis: {
          type: 'value',
          min: -0.1,
          max: 1.1,
          show: false
        },
        yAxis: {
          type: 'value',
          min: -0.1,
          max: Math.sqrt(3) / 2 + 0.1,
          show: false
        },
        series: [
          triangleBorder,
          ...gridLines,
          labelSeries,
          ...scatterSeries
        ]
      };

      chart.setOption(option);

      const resizeHandler = () => {
        if (chart && !chart.isDisposed()) {
          chart.resize();
        }
      };
      window.addEventListener('resize', resizeHandler);

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart10) {
          this.chart10.dispose();
          this.chart10 = null;
        }
      });

      setTimeout(() => {
        if (chart && !chart.isDisposed()) {
          this.ht10Url = chart.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff',
          });
        }
      }, 1000);
    },

    // <!-----------------------------------------图八：气泡颜色映射图相关方法-------------------------------------------------------------------------->
    // ========== 点击表格行 ==========
    htTableClick10(row, column, event) {
      console.log('图表8点击行数据:', row);
      console.log(`样品: ${row.section}`);
      console.log(`气泡总数: ${row.bubble_total || 0}`);
      console.log(`详细气泡数据: ${row.bubbles ? row.bubbles.length : 0} 个`);
      
      // ✅ 优化：直接使用表格数据，移除冗余的后端请求
      if (!row.bubbles || row.bubbles.length === 0) {
        this.$message.warning('该样品没有气泡数据');
        // 清空图表
        if (this.chart11) {
          this.chart11.clear();
        }
        return;
      }
      
      // 直接传入当前行数据进行绘图
      this.initEcharts10([row]);
    },

    // =========================================== 图八：气泡颜色映射图 ==========
    initEcharts10(values) {
      // 🔴 空值处理
      if (!values || values.length === 0) {
        if (this.chart11) {
          this.chart11.clear();
          this.chart11.dispose();
          this.chart11 = null;
        }
        return;
      }

      // 🔴 销毁已存在的图表
      if (this.chart11) {
        this.chart11.dispose();
        this.chart11 = null;
      }

      // 🔴 获取DOM并初始化
      const chartDom = this.$refs.chart11;
      if (!chartDom) {
        console.error('Chart11 DOM element not found');
        return;
      }

      const chart = echarts.init(chartDom);
      this.chart11 = chart;

      // 🎨 颜色映射表（高对比度四色方案）
    const baseColorMap = {
      'lt2': {
        base: '#FF1744',      // 鲜红色（最小气泡）
        light: '#FF5252',
        mid: '#FF1744',
        dark: '#D50000'
      },
      '2to5': {
        base: '#00E676',      // 鲜绿色（中小气泡）
        light: '#69F0AE',
        mid: '#00E676',
        dark: '#00C853'
      },
      '5to10': {
        base: '#2979FF',      // 鲜蓝色（中大气泡）
        light: '#448AFF',
        mid: '#2979FF',
        dark: '#2962FF'
      },
      'gt10': {
        base: '#FF9100',      // 鲜橙色（最大气泡）
        light: '#FFAB40',
        mid: '#FF9100',
        dark: '#FF6D00'
      }
    };

      // 🎨 尺寸范围名称映射
      const nameMap = {
        'lt2': '<2μm',
        '2to5': '2~5μm',
        '5to10': '5~10μm',
        'gt10': '>10μm'
      };

      // ✅ 优化：按尺寸范围分组数据
      const seriesData = {
        'lt2': [],
        '2to5': [],
        '5to10': [],
        'gt10': []
      };

      // 统计信息
      const statistics = {
        'lt2': { count: 0, minEcd: Infinity, maxEcd: -Infinity, avgEcd: 0 },
        '2to5': { count: 0, minEcd: Infinity, maxEcd: -Infinity, avgEcd: 0 },
        '5to10': { count: 0, minEcd: Infinity, maxEcd: -Infinity, avgEcd: 0 },
        'gt10': { count: 0, minEcd: Infinity, maxEcd: -Infinity, avgEcd: 0 }
      };

      let totalBubbles = 0;
      let xMin = Infinity, xMax = -Infinity;
      let yMin = Infinity, yMax = -Infinity;
      let ecdMin = Infinity, ecdMax = -Infinity;

      // 🔴 遍历所有样品（通常只有一个）
      values.forEach(item => {
        console.log(`处理样品: ${item.section}`);
        
        if (!item.bubbles || item.bubbles.length === 0) {
          console.warn('该样品没有气泡数据');
          return;
        }

        // ✅ 遍历每个气泡（而不是只统计数量）
        item.bubbles.forEach(bubble => {
          const range = bubble.size_range;
          
          // 数据验证
          if (!range || !baseColorMap[range]) {
            console.warn('气泡尺寸范围无效:', bubble);
            return;
          }

          const ecd = parseFloat(bubble.ecd);
          const x = parseFloat(bubble.x);
          const y = parseFloat(bubble.y);

          // ✅ 使用真实的坐标和ECD
          seriesData[range].push([x, y, ecd]);

          // 更新统计信息
          statistics[range].count++;
          statistics[range].minEcd = Math.min(statistics[range].minEcd, ecd);
          statistics[range].maxEcd = Math.max(statistics[range].maxEcd, ecd);
          statistics[range].avgEcd += ecd;

          totalBubbles++;

          // 计算坐标范围（用于自动设置坐标轴范围）
          xMin = Math.min(xMin, x);
          xMax = Math.max(xMax, x);
          yMin = Math.min(yMin, y);
          yMax = Math.max(yMax, y);
          ecdMin = Math.min(ecdMin, ecd);
          ecdMax = Math.max(ecdMax, ecd);
        });
      });

      // 计算平均值
      Object.keys(statistics).forEach(range => {
        if (statistics[range].count > 0) {
          statistics[range].avgEcd = statistics[range].avgEcd / statistics[range].count;
        }
      });

      console.log(`总气泡数: ${totalBubbles}`);
      console.log(`X范围: ${xMin.toFixed(2)} ~ ${xMax.toFixed(2)}`);
      console.log(`Y范围: ${yMin.toFixed(2)} ~ ${yMax.toFixed(2)}`);
      console.log(`ECD范围: ${ecdMin.toFixed(2)} ~ ${ecdMax.toFixed(2)}`);

      // 打印每个尺寸范围的统计
      Object.keys(seriesData).forEach(range => {
        if (statistics[range].count > 0) {
          console.log(`${nameMap[range]}: ${statistics[range].count} 个, ` +
                      `ECD: ${statistics[range].minEcd.toFixed(2)}~${statistics[range].maxEcd.toFixed(2)}μm, ` +
                      `平均: ${statistics[range].avgEcd.toFixed(2)}μm`);
        }
      });

      // 🎨 渐变颜色函数（优化2：根据ECD渐变）
      const getGradientColor = (range, ecd) => {
        const colors = baseColorMap[range];
        
        // 根据该范围内ECD的相对位置返回渐变颜色
        let minEcd, maxEcd;
        
        switch(range) {
          case 'lt2':
            minEcd = 0;
            maxEcd = 2;
            break;
          case '2to5':
            minEcd = 2;
            maxEcd = 5;
            break;
          case '5to10':
            minEcd = 5;
            maxEcd = 10;
            break;
          case 'gt10':
            minEcd = 10;
            maxEcd = statistics[range].maxEcd || 20;
            break;
        }
        
        // 计算在范围内的位置（0~1）
        const ratio = (ecd - minEcd) / (maxEcd - minEcd);
        
        if (ratio < 0.33) {
          return colors.light;  // 浅色（小气泡）
        } else if (ratio < 0.67) {
          return colors.mid;    // 中色（中等气泡）
        } else {
          return colors.dark;   // 深色（大气泡）
        }
      };

      // 🔴 构建系列（每个尺寸范围一个系列）
      const series = [];
      const legendData = [];

      Object.keys(seriesData).forEach(range => {
        if (seriesData[range].length > 0) {
          const name = nameMap[range];
          
          // 🔴🔴🔴 修改：添加图例数据（包含颜色信息）🔴🔴🔴
          legendData.push({
            name: name,
            itemStyle: {
              color: baseColorMap[range].mid  // 使用中间色作为图例颜色
            }
          });
          // 🔴🔴🔴 修改结束 🔴🔴🔴

          series.push({
            name: name,
            type: 'scatter',
            data: seriesData[range],
            
            // 🔴🔴🔴 优化：固定大小（差异明显）🔴🔴🔴
            symbolSize: function(data) {
              const ecd = data[2];
              
              if (ecd < 2) {
                return 6;            // <2μm：小点
              } else if (ecd < 5) {
                return 12;           // 2~5μm：中点（2倍）
              } else if (ecd < 10) {
                return 18;           // 5~10μm：大点（3倍）
              } else {
                return 26;           // >10μm：超大点（4.3倍）
              }
            },
            // 🔴🔴🔴 修改结束 🔴🔴🔴
            
            // ✅ 优化2：根据ECD渐变颜色
            itemStyle: {
              color: function(params) {
                const ecd = params.data[2];
                return getGradientColor(range, ecd);
              },
              opacity: 0.75,
              borderWidth: 0.5,
              borderColor: 'rgba(255,255,255,0.8)'
            },
            
            // ✅ 添加高亮效果
            emphasis: {
              itemStyle: {
                opacity: 1,
                borderColor: '#333',
                borderWidth: 2,
                shadowBlur: 10,
                shadowColor: 'rgba(0,0,0,0.3)'
              },
              scale: 1.2  // 放大1.2倍
            }
          });
        }
      });

      // 🔴 如果没有任何数据，显示提示
      if (series.length === 0) {
        this.$message.warning('没有可显示的气泡数据');
        chart.clear();
        return;
      }

      // 🔴 计算坐标轴范围（添加10%的边距）
      const xPadding = (xMax - xMin) * 0.1 || 10;
      const yPadding = (yMax - yMin) * 0.1 || 10;

      // ✅ 优化3：构建统计信息面板
      const statisticsText = [
        `总气泡数: ${totalBubbles}`,
        '',
        ...Object.keys(statistics).map(range => {
          if (statistics[range].count > 0) {
            return `${nameMap[range]}: ${statistics[range].count}个\n` +
                  `  平均: ${statistics[range].avgEcd.toFixed(2)}μm\n` +
                  `  范围: ${statistics[range].minEcd.toFixed(2)}~${statistics[range].maxEcd.toFixed(2)}μm`;
          }
          return null;
        }).filter(text => text !== null)
      ].join('\n');

      const option = {
        // 🔴 标题
        title: {
          text: values[0].section ? `样品: ${values[0].section}` : '气泡分布图',
          left: 'center',
          top: '8%',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman',
            color: '#2e2d2d'
          }
        },
        
        // 🔴 Tooltip（鼠标悬停提示）
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const ecd = params.data[2];
            const x = params.data[0];
            const y = params.data[1];
            
            return `<div style="padding: 8px;">
                      <div style="font-weight: bold; margin-bottom: 6px; color: #333;">
                        ${params.seriesName}
                      </div>
                      <div style="line-height: 1.6;">
                        <span style="color: #666;">ECD:</span> 
                        <span style="font-weight: 600; color: #2e2d2d;">${ecd.toFixed(3)} μm</span><br/>
                        <span style="color: #666;">位置 X:</span> 
                        <span style="color: #2e2d2d;">${x.toFixed(2)} μm</span><br/>
                        <span style="color: #666;">位置 Y:</span> 
                        <span style="color: #2e2d2d;">${y.toFixed(2)} μm</span>
                      </div>
                    </div>`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.96)',
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 13
          },
          extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.15); border-radius: 4px;'
        },
        
        // 🔴 图例（右上角）
        legend: {
        orient: 'vertical',
        right: '3%',        // ✅ 调整右边距
        top: '8%',          // ✅ 调整上边距
        backgroundColor: 'rgba(255,255,255,0.92)',
        borderColor: 'rgba(200,200,200,0.6)',
        borderWidth: 1,
        borderRadius: 6,
        padding: [12, 15, 12, 15],  // ✅ 增大内边距
        data: legendData,
        textStyle: {
          fontSize: 18,     // ✅ 增大字体
          fontWeight: 'bold',        
          fontFamily: 'Times New Roman'
        },
        selected: legendData.reduce((obj, item) => {
          const name = typeof item === 'string' ? item : item.name;
          obj[name] = true;
          return obj;
        }, {}),
        itemGap: 15,        // ✅ 增大图例项间距
        itemWidth: 20,      // ✅ 增大图例图标宽度
        itemHeight: 14      // ✅ 增大图例图标高度
      },
        
        // 🔴 网格区域
        grid: {
          top: '15%',
          left: '25%',
          right: '25%',
          bottom: '15%',
          borderWidth: 2.5,
          borderColor: '#333333',
          show: true,
          containLabel: false
        },
        
        // 🔴 X轴
        xAxis: {
          type: 'value',
          name: 'X坐标',
          nameLocation: 'middle',
          nameGap: 45,
          
          // ✅ 根据数据自动设置范围
          min: Math.floor(xMin - xPadding),
          max: Math.ceil(xMax + xPadding),
          
          axisTick: {
            show: true,
            inside: true,
            length: 5
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#333',
              width: 2
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f5f5f5',  // 极浅灰色
              type: 'solid',  // 'solid' | 'dashed' | 'dotted'
              width: 1
            }
          },
          nameTextStyle: {
            padding: [5, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          axisLabel: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman',
            formatter: '{value}'
          }
        },
        
        // 🔴 Y轴
        yAxis: {
          type: 'value',
          name: 'Y坐标',
          nameLocation: 'middle',
          nameRotate: 90,
          nameGap: 50,
          
          // ✅ 根据数据自动设置范围
          min: Math.floor(yMin - yPadding),
          max: Math.ceil(yMax + yPadding),
          
          axisTick: {
            show: true,
            inside: true,
            length: 5
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#333',
              width: 2
            }
          },
          splitLine: {
          show: true,
            lineStyle: {
              color: '#f5f5f5',  // 极浅灰色
              type: 'solid',  // 'solid' | 'dashed' | 'dotted'
              width: 1
            }
          },
          nameTextStyle: {
            align: 'center',
            padding: [0, 0, 0, 0],
            color: '#2e2d2d',
            fontSize: 24,
            fontWeight: 'bold',
            fontFamily: 'Times New Roman'
          },
          axisLabel: {
            formatter: '{value}',
            fontSize: 16,
            fontWeight: 'bold',
            color: '#2e2d2d',
            fontFamily: 'Times New Roman'
          }
        },
        
        // 🔴 系列数据
        series: series,
        
        // ✅ 添加工具栏
        // 在 option 对象中替换 toolbox 部分
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              show: true,
              title: '下载图片',
              name: `气泡分布图_${values[0].section}_${new Date().getTime()}`,
              pixelRatio: 2,
              backgroundColor: '#fff'
            }
          },
          left: 20,          // 左下角
          bottom: 20,
          itemSize: 28,      // 图标大小
          iconStyle: {
            borderColor: '#1890ff',
            borderWidth: 2,
            shadowBlur: 5,
            shadowColor: 'rgba(24, 144, 255, 0.3)'
          },
          emphasis: {
            iconStyle: {
              borderColor: '#096dd9',
              borderWidth: 3,
              shadowBlur: 12,
              shadowColor: 'rgba(24, 144, 255, 0.6)'
            }
          },
          tooltip: {
            show: true,
            formatter: '点击下载高清图片',
            backgroundColor: 'rgba(24, 144, 255, 0.95)',
            textStyle: {
              color: '#fff',
              fontSize: 14,
              fontWeight: 'bold'
            },
            extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.3); border-radius: 6px; padding: 8px 12px;'
          }
        },
        
        // ✅ 添加区域缩放组件
        dataZoom: [
          {
            type: 'inside',  // 内置缩放（鼠标滚轮）
            xAxisIndex: 0,
            filterMode: 'none'
          },
          {
            type: 'inside',
            yAxisIndex: 0,
            filterMode: 'none'
          }
        ],
        
        // ✅ 优化3：添加统计信息面板
        graphic: [
          {
            type: 'group',
            right:'3%',
            bottom: '3%',
            children: [
              // 背景矩形
              {
                type: 'rect',
                z: 100,
                left: 0,
                top: 0,
                shape: {
                  width: 260,
                  height: 38 + Object.keys(statistics).filter(r => statistics[r].count > 0).length * 78
                },
                style: {
                  fill: 'rgba(255, 255, 255, 0.95)',
                  stroke: 'rgba(180, 180, 180, 0.7)',
                  lineWidth: 1.5,
                  shadowBlur: 10,
                  shadowColor: 'rgba(0, 0, 0, 0.15)',
                  shadowOffsetX: 2,
                  shadowOffsetY: 2
                }
              },
              // 统计文本
              {
                type: 'text',
                z: 101,
                left: 70,
                top: 18,
                style: {
                  text: statisticsText,
                  fontSize: 16,
                  fontWeight: 'bold',
                  fontFamily: 'Arial, Microsoft YaHei, sans-serif', 
                  fill: '#2e2d2d',
                  lineHeight: 22,
                  textAlign: 'left',  // ✅ 新增：文字居中对齐
                  textVerticalAlign: 'top',  // ✅ 新增：文字顶部对齐
                  rich: {
                    title: {
                      fontSize: 14,
                      fontWeight: 'bold',
                      padding: [0, 0, 5, 0],                  
                    }
                  }
                }
              }
            ]
          }
        ]
      };

      chart.setOption(option);

      // 🔴 添加resize监听
      const resizeHandler = () => {
        chart.resize();
      };
      window.addEventListener('resize', resizeHandler);

      // 🔴 组件销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
        if (this.chart11) {
          this.chart11.dispose();
          this.chart11 = null;
        }
      });

      // 🔴 生成图片URL（用于导出）
      setTimeout(() => {
        try {
          this.ht10Url = chart.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#fff'
          });
          console.log('✅ 图表图片生成成功');
        } catch (error) {
          console.error('❌ 生成图表图片失败:', error);
        }
      }, 1000);
    },

  },    
};

</script>

<style scoped lang="scss">

/* 只针对统计错误消息的字体大小 */
::v-deep .statistic-error-message {
  font-size: 18px !important; /* 调整为您想要的大小 */
}
.bar-chart {
  margin: 20px;
}

.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

.el-form-item {
  height: 40px;
  align-items: flex-start;
}

.el-form > div {
  min-height: 40px;
  max-height: 40px;
  align-items: flex-start;
}

.el-select {
  height: 40px;
  
  .el-input__inner {
    height: 40px;
    line-height: 40px;
  }
}

</style>

